Securing Headers with Helmet
Helmet sets protective HTTP headers with a single line.
Syntax
app.use(helmet())Helmet is a middleware that sets a collection of security-related HTTP headers, such as those that prevent clickjacking and reduce the risk of cross-site scripting. It is an easy, high-value first step for any Express app.
Install with npm install helmet and add it near the top of your middleware stack.
Example
const helmet = require('helmet');
app.use(helmet()); // sets many secure headers at once
app.get('/', (req, res) => res.send('Secured'));When to use it
- A public-facing Express app uses Helmet to set a strict Content-Security-Policy that blocks inline scripts and only allows known CDN sources.
- A developer adds Helmet as the very first middleware so security headers are present on every response including error pages.
- A team uses Helmet's HSTS middleware with a long maxAge to instruct browsers to always use HTTPS for their domain.
More examples
Add Helmet with defaults
Calls helmet() with no arguments to apply all 11 default security headers including CSP, HSTS, and X-Frame-Options.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Register before all other middleware
app.use(helmet());
app.get('/', (req, res) => res.send('Secure'));
app.listen(3000);Custom CSP with Helmet
Configures a custom Content-Security-Policy that permits scripts only from self and a CDN, hardening against XSS.
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'https://cdn.jsdelivr.net'],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", 'data:', 'https://img.example.com'],
},
}));HSTS with long maxAge
Sets HTTP Strict Transport Security with a 1-year max-age and preload flag to enrol the domain in browser HSTS preload lists.
app.use(helmet.hsts({
maxAge: 31536000, // 1 year in seconds
includeSubDomains: true,
preload: true,
}));
Discussion