JAVASCRIPT
Enforce Essential HTTP Security Headers in Express.js
Strengthen your web application's defense against common attacks by automatically setting critical HTTP security headers using Helmet middleware in Express.js.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various security headers
app.use(helmet()); // Enables all default Helmet middlewares
// You can customize individual headers if needed, e.g.:
// app.use(helmet.hidePoweredBy()); // Remove X-Powered-By header
// app.use(helmet.frameguard({ action: 'deny' })); // Prevent clickjacking
// app.use(helmet.xssFilter()); // X-XSS-Protection header (Helmet defaults to 0)
// app.use(helmet.noSniff()); // X-Content-Type-Options header
// app.use(helmet.hsts({
// maxAge: 31536000, // 1 year in seconds
// includeSubDomains: true,
// preload: true
// })); // HTTP Strict Transport Security
app.get('/', (req, res) => {
res.send('<h1>Essential Security Headers Example</h1><p>Inspect your browser\'s network tab to see the security headers.</p>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running with security headers on port ${PORT}`);
console.log('Visit http://localhost:3000');
});
How it works: This snippet demonstrates how to easily implement a suite of essential HTTP security headers in an Express.js application using the `helmet` middleware. `helmet()` enables multiple security middlewares by default, adding headers like `X-Content-Type-Options: nosniff` (to prevent MIME-sniffing attacks), `X-Frame-Options: SAMEORIGIN` (to prevent clickjacking), `X-XSS-Protection: 0` (modern browsers typically handle XSS protection, so disabling browser-native filters is often safer alongside CSP), and `Strict-Transport-Security` (HSTS) which forces browsers to use HTTPS. These headers provide an additional layer of defense against common web vulnerabilities.