JAVASCRIPT
Configure Essential Security HTTP Headers in Express
Enhance web application security by setting critical HTTP headers like HSTS, CSP, X-Frame-Options, and X-Content-Type-Options using Helmet.js in Express.
const express = require('express');
const helmet = require('helmet'); // npm install helmet
const app = express();
// Use Helmet to set various HTTP headers for security
app.use(helmet());
// You can customize specific headers
app.use(helmet.frameguard({ action: 'deny' })); // X-Frame-Options: DENY
app.use(helmet.xssFilter()); // X-XSS-Protection: 1; mode=block
app.use(helmet.noSniff()); // X-Content-Type-Options: nosniff
app.use(helmet.hsts({ // HTTP Strict Transport Security
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: false // Set to true if you want to submit your domain to the HSTS preload list
}));
app.use(helmet.dnsPrefetchControl({ allow: false }));
// Example of a custom Content Security Policy (CSP)
// IMPORTANT: CSP needs careful configuration. Start with a report-only mode.
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "https://trusted-cdn.com"], // Be very specific
styleSrc: ["'self'", "https://trusted-cdn.com"],
imgSrc: ["'self'", "data:", "https://trusted-images.com"],
formAction: ["'self'"],
objectSrc: ["'none'"],
upgradeInsecureRequests: [], // Automatically upgrade HTTP to HTTPS
},
reportOnly: false, // Set to true initially to monitor violations without blocking
})
);
app.get('/', (req, res) => {
res.send('<h1>Secure Page</h1><p>Check your network tab for security headers!</p>');
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
How it works: This snippet shows how to easily add a robust set of security HTTP headers to an Express.js application using the `helmet` middleware. It configures headers like HSTS, X-Frame-Options, X-XSS-Protection, X-Content-Type-Options, and a Content Security Policy (CSP) to mitigate various common web vulnerabilities like clickjacking, XSS, and content injection.