JAVASCRIPT
Implement Essential Security Headers with Helmet in Node.js Express
Enhance your Node.js Express application's security by automatically setting crucial HTTP headers like CSP, HSTS, and X-Frame-Options using the Helmet middleware.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set various security-related HTTP headers
// Helmet is a collection of 15 smaller middlewares
app.use(helmet());
// You can also configure specific Helmet middlewares individually
// For example, setting a custom Content Security Policy (CSP)
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "'unsafe-eval'", "https://trusted.cdn.com"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https://images.example.com"],
connectSrc: ["'self'", "wss://api.example.com"],
fontSrc: ["'self'", "https://fonts.gstatic.com"],
objectSrc: ["'none'"],
upgradeInsecureRequests: [], // Automatically rewrite HTTP to HTTPS
},
}));
// Example: Explicitly set X-Frame-Options to DENY
// (Helmet's default x-frame-options is 'DENY', but this shows customization)
app.use(helmet.xFrameOptions({ action: 'DENY' }));
// Example: Set Strict-Transport-Security (HSTS) - forces HTTPS for a duration
// (Helmet's default hsts is enabled with maxAge: 180 days, includeSubDomains: true)
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true
}));
app.get('/', (req, res) => {
res.send('Hello Secure World!');
});
app.get('/unsafe', (req, res) => {
// This route would inherit the security headers from helmet()
res.send('<img src="x" onerror="alert(\'XSS in unsafe page!\')">'); // CSP would block this
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
console.log(`Check headers at http://localhost:${PORT}`);
});
/*
To install dependencies:
npm install express helmet
*/
How it works: This Node.js Express snippet demonstrates how to significantly improve application security by implementing essential HTTP security headers using the `helmet` middleware. `helmet` automatically sets headers like X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security (HSTS), and a robust Content Security Policy (CSP), protecting against common attacks such as XSS, clickjacking, and insecure communication by enforcing best practices for browser behavior.