← Back to all snippets
JAVASCRIPT

Implementing Essential HTTP Security Headers

Configure critical HTTP security headers like HSTS, X-Frame-Options, and X-Content-Type-Options to protect web applications against common attacks like clickjacking and MIME-type sniffing.

// Example in Node.js Express using 'helmet' middleware
const express = require('express');
const helmet = require('helmet');

const app = express();

// Apply Helmet middleware for various security headers
app.use(helmet());

// Example of configuring specific headers (Helmet handles most by default)
// Force all connections to use HTTPS for a year
app.use(helmet.hsts({
  maxAge: 31536000, // 1 year in seconds
  includeSubDomains: true,
  preload: true
}));

// Prevent clickjacking by disallowing framing of the page
app.use(helmet.frameguard({ action: 'deny' }));

// Prevent browsers from MIME-sniffing a response away from the declared content-type
app.use(helmet.noSniff());

// Other headers often set by default with helmet() include:
// X-XSS-Protection: 1; mode=block (Deprecated, CSP is better)
// Referrer-Policy: no-referrer (Can be customized)
// X-Download-Options: noopen (IE only)

app.get('/', (req, res) => {
  res.send('Hello Secure World!');
});

app.listen(3000, () => console.log('Server running with security headers on port 3000'));
How it works: This Node.js Express snippet demonstrates how to easily implement crucial HTTP security headers using the `helmet` middleware. `helmet.hsts` enforces HTTP Strict Transport Security (HSTS), compelling browsers to interact only over HTTPS, preventing downgrade attacks. `helmet.frameguard({ action: 'deny' })` sets the X-Frame-Options header to `DENY`, protecting against clickjacking. `helmet.noSniff()` sets X-Content-Type-Options to `nosniff`, preventing browsers from misinterpreting MIME types, which can lead to XSS vulnerabilities.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs