JAVASCRIPT
Configure HTTP Security Headers with Helmet.js in Express
Enhance the security of your Node.js Express application by automatically setting critical HTTP security headers like HSTS, X-Content-Type-Options, and X-Frame-Options using the Helmet.js middleware.
const express = require('express');
const helmet = require('helmet'); // npm install helmet
const app = express();
// Use Helmet to set various security headers
app.use(helmet());
// You can also configure individual Helmet middleware for more control
// app.use(helmet.contentSecurityPolicy()); // Already included in default helmet()
// app.use(helmet.dnsPrefetchControl());
// app.use(helmet.frameguard({ action: 'deny' })); // Prevents clickjacking
// app.use(helmet.hidePoweredBy()); // Removes X-Powered-By header
// app.use(helmet.hsts({
// maxAge: 31536000, // 1 year in seconds
// includeSubDomains: true,
// preload: true
// })); // Enforces HTTPS
// app.use(helmet.noSniff()); // Prevents MIME type sniffing
// app.use(helmet.xssFilter()); // Adds X-XSS-Protection header (deprecated, but still used by some older browsers)
// Example route
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
const PORT = 3000;
app.listen(PORT, () => console.log(`Server running with Helmet.js on http://localhost:${PORT}`));
How it works: This snippet demonstrates how to quickly add a layer of security to an Express application by leveraging the `helmet` middleware. By simply calling `app.use(helmet())`, a suite of default HTTP security headers (e.g., HSTS, X-Content-Type-Options, X-Frame-Options, X-DNS-Prefetch-Control, etc.) is automatically configured. These headers help mitigate common web vulnerabilities like clickjacking, cross-site scripting (XSS), and insecure connections. Individual middleware functions can be used for fine-grained control over each header.