JAVASCRIPT
Implement Essential HTTP Security Headers in Node.js
Enhance web application security by implementing critical HTTP headers like HSTS, X-Frame-Options, and X-Content-Type-Options in Node.js Express to protect users.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various security headers
// Note: Helmet includes many headers, but here we focus on specific ones.
app.use(helmet.frameguard({ action: 'deny' })); // Prevents clickjacking by disallowing embedding in iframes
app.use(helmet.noSniff()); // Prevents browsers from MIME-sniffing a response away from the declared Content-Type
app.use(helmet.xssFilter()); // Adds basic XSS protection (though client-side XSS prevention is more robust)
// Manually set Strict-Transport-Security for HTTPS enforcement
// Recommended for production after successful HTTPS setup
app.use((req, res, next) => {
res.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains; preload');
next();
});
// Example route
app.get('/', (req, res) => {
res.send('Hello, secure web!');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js Express snippet demonstrates how to implement essential HTTP security headers using the `helmet` middleware and by manually setting the `Strict-Transport-Security` header. `helmet.frameguard` prevents clickjacking, `helmet.noSniff` mitigates MIME-sniffing attacks, and `helmet.xssFilter` adds basic XSS protection. The `Strict-Transport-Security` header enforces HTTPS, instructing browsers to only connect over secure channels, significantly reducing the risk of man-in-the-middle attacks. These headers fortify your application's defense against common web vulnerabilities.