JAVASCRIPT
Implementing Essential HTTP Security Headers (Node.js/Express)
Protect your web application from common attacks by implementing critical HTTP security headers like CSP, HSTS, and X-Frame-Options using Helmet.js in Express.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various HTTP headers
app.use(helmet());
// Further customize specific headers if needed
// Content Security Policy (CSP)
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'", 'trusted-cdn.com'],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'another-domain.com'],
connectSrc: ["'self'", 'api.example.com'],
objectSrc: ["'none'"],
upgradeInsecureRequests: [], // Ensures all HTTP requests are upgraded to HTTPS
},
})
);
// HTTP Strict Transport Security (HSTS)
// Forces browsers to use HTTPS for a specified duration
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true,
}));
// X-Frame-Options to prevent clickjacking
app.use(helmet.frameguard({ action: 'deny' }));
// X-Content-Type-Options to prevent MIME type sniffing
app.use(helmet.noSniff());
// X-XSS-Protection (often handled by CSP, but good as a fallback for older browsers)
app.use(helmet.xssFilter());
// Example route
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js Express snippet uses the 'helmet' middleware to automatically set a variety of HTTP security headers. These headers protect against common web vulnerabilities like Cross-Site Scripting (XSS), Clickjacking, MIME type sniffing, and insecure connections. Key headers configured include Content Security Policy (CSP) to mitigate XSS by controlling resource loading, HTTP Strict Transport Security (HSTS) to enforce HTTPS, and X-Frame-Options to prevent embedding your site in iframes. Always customize CSP directives carefully to avoid blocking legitimate resources.