JAVASCRIPT
Implement Essential HTTP Security Headers in Node.js Express
Enhance web application security by implementing critical HTTP security headers like CSP, HSTS, X-Frame-Options, and X-XSS-Protection using Helmet middleware in Express.js.
const express = require('express');
const helmet = require('helmet'); // Helmet is a collection of 14 small middleware functions that set HTTP headers
const app = express();
const port = 3000;
// Use Helmet to set a variety of security-related HTTP headers
app.use(helmet());
// You can customize individual headers if needed, for example, CSP
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://trusted-cdn.com"],
styleSrc: ["'self'", "'unsafe-inline'"], // Be cautious with 'unsafe-inline'
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"], // Prevents embedding in iframes
workerSrc: ["'self'"],
manifestSrc: ["'self'"],
reportUri: "/csp-report-endpoint" // Optional: where to send CSP violation reports
}
}));
// HSTS (Strict-Transport-Security) is enabled by default with helmet() but can be customized:
// app.use(helmet.hsts({
// maxAge: 31536000, // 1 year in seconds
// includeSubDomains: true,
// preload: true
// }));
app.get('/', (req, res) => {
res.send('<h1>Hello Secure World!</h1><p>Check your network tab for security headers.</p>');
});
// An example endpoint for CSP violation reports
app.post('/csp-report-endpoint', express.json({ type: 'application/csp-report' }), (req, res) => {
console.log('CSP Violation Report:', req.body);
res.status(204).send();
});
app.listen(port, () => {
console.log(`Secure app listening at http://localhost:${port}`);
});
How it works: This Node.js Express snippet demonstrates how to implement crucial HTTP security headers using the `helmet` middleware. `helmet()` by default sets headers like `X-Content-Type-Options`, `X-Frame-Options`, `Strict-Transport-Security`, `X-XSS-Protection`, and `Referrer-Policy`. The example also shows how to customize a `Content-Security-Policy` (CSP) header, which helps mitigate XSS and data injection attacks by restricting which resources a browser is allowed to load. Properly configured headers are a fundamental layer of defense against various web vulnerabilities.