JAVASCRIPT
Configure Essential HTTP Security Headers in Node.js Express
Enhance web application security by setting critical HTTP headers like CSP, HSTS, and X-Frame-Options using Helmet in Node.js Express.
const express = require('express');
const helmet = require('helmet'); // Helmet helps secure Express apps by setting various HTTP headers
const app = express();
const port = 3000;
// Use Helmet to set various security headers.
// Helmet is a collection of 14 smaller middleware functions that set security-related HTTP headers.
app.use(helmet());
// --- Customizing specific Helmet middleware ---
// 1. Content Security Policy (CSP): Prevents XSS, clickjacking, and other injection attacks
// Define sources for various content types. Be as strict as possible.
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"], // Be very cautious with 'unsafe-inline'
styleSrc: ["'self'", "https://trusted-cdn.com"],
imgSrc: ["'self'", "data:", "https://trusted-images.com"],
fontSrc: ["'self'", "https://trusted-fonts.com"],
objectSrc: ["'none'"], // Disallow <object>, <embed>, <applet>
upgradeInsecureRequests: [], // Automatically upgrade HTTP requests to HTTPS
},
}));
// 2. HTTP Strict Transport Security (HSTS): Enforces HTTPS for future requests
// maxAge is in seconds (e.g., 31536000 for 1 year)
// includeSubDomains: Apply HSTS to all subdomains as well
// preload: Opt-in to browser preload lists for maximum protection
app.use(helmet.hsts({
maxAge: 31536000,
includeSubDomains: true,
preload: true,
}));
// 3. X-Frame-Options: Prevents clickjacking attacks by forbidding embedding the site in iframes
// 'DENY': No framing
// 'SAMEORIGIN': Frame only if the origin is the same as the page itself
app.use(helmet.frameguard({ action: 'deny' }));
// 4. X-Content-Type-Options: Prevents browsers from "sniffing" a response away from the declared content-type
// Prevents MIME-sniffing vulnerabilities
app.use(helmet.noSniff());
// Other useful Helmet headers (many are enabled by default with app.use(helmet())):
// - X-DNS-Prefetch-Control: Disables DNS prefetching (reduces privacy risk)
// - X-Powered-By: Removes this header (reduces fingerprinting)
// - Referrer-Policy: Controls referrer information sent with requests
app.get('/', (req, res) => {
res.send('<h1>Secure Express App</h1><p>Check your browser\'s developer tools (Network tab) to see the security headers.</p>');
});
app.listen(port, () => {
console.log(`Secure server running at http://localhost:${port}`);
console.log('Remember to use HTTPS in production for full HSTS benefits.');
});
How it works: Setting appropriate HTTP security headers is crucial for protecting web applications against various attacks. This Node.js Express snippet uses the `helmet` middleware to easily configure essential headers. `Content-Security-Policy` (CSP) mitigates Cross-Site Scripting (XSS) and data injection by restricting resource loading. `HTTP-Strict-Transport-Security` (HSTS) enforces HTTPS, preventing downgrade attacks. `X-Frame-Options` prevents clickjacking by controlling if a page can be framed. `X-Content-Type-Options` prevents MIME-sniffing, reducing vulnerabilities related to incorrect content interpretation. Helmet provides a robust and convenient way to implement these protections.