JAVASCRIPT
Implement Essential HTTP Security Headers in Node.js with Helmet
Enhance web application security by implementing critical HTTP security headers like HSTS, X-Frame-Options, and X-Content-Type-Options in an Express.js application using the Helmet middleware.
const express = require('express');
const helmet = require('helmet');
const app = express();
const PORT = 3000;
// Use Helmet middleware to set various HTTP headers for security
app.use(helmet());
// Helmet sets most security headers by default. You can customize them if needed.
// Example of custom configuration for specific headers:
app.use(helmet.frameguard({ action: 'deny' })); // Prevents clickjacking by blocking IFRAME embedding
app.use(helmet.xssFilter()); // Adds X-XSS-Protection header for browser's XSS filter
app.use(helmet.noSniff()); // Prevents browsers from MIME-sniffing a response away from the declared content-type
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true
})); // Enforces secure (HTTPS) connections to the server
// Note: Content Security Policy (CSP) is handled by helmet.contentSecurityPolicy().
// It's a powerful but complex header. For basic setup without CSP:
// app.use(helmet.contentSecurityPolicy({
// directives: {
// defaultSrc: ["'self'"],
// scriptSrc: ["'self'"],
// // ... other directives
// }
// }));
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
app.listen(PORT, () => {
console.log(`Server running with security headers on http://localhost:${PORT}`);
console.log('Test headers with: curl -I http://localhost:3000');
});
How it works: This Node.js snippet demonstrates how to easily implement several crucial HTTP security headers using the `helmet` middleware for Express.js. `helmet` helps protect your application from common web vulnerabilities by setting headers like `X-Frame-Options` (preventing clickjacking), `X-XSS-Protection` (enabling browser's XSS filter), `X-Content-Type-Options` (disabling MIME-sniffing), and `Strict-Transport-Security` (HSTS, enforcing HTTPS). By default, `helmet()` applies a set of recommended headers, and you can further customize individual headers as shown for enhanced security.