Security Headers with Helmet
8 min read
Security Headers with Helmet
Helmet is a collection of small middleware functions that each set a security-related HTTP response header. A single app.use(helmet()) call adds roughly a dozen headers that protect against common web vulnerabilities with zero configuration.
js
const helmet = require("helmet");
// Sensible defaults — use this in every Express app
app.use(helmet());Headers Helmet Sets by Default
Content-Security-Policy— restricts where scripts, styles, and images may load from (XSS defence)X-Content-Type-Options: nosniff— prevents MIME-type sniffingX-Frame-Options: SAMEORIGIN— blocks clickjacking via iframesStrict-Transport-Security— forces HTTPS after the first connection (HSTS)Referrer-Policy: no-referrer— avoids leaking URLs in the Referer headerX-DNS-Prefetch-Control: off— disables browser DNS prefetching
Customising CSP for Your App
js
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "https://cdn.jsdelivr.net"],
imgSrc: ["'self'", "data:", "https://res.cloudinary.com"],
styleSrc: ["'self'", "'unsafe-inline'"]
}
}
})
);Mount helmet() as the very first middleware in app.ts, before routes and body parsers. Security headers should be sent on every response, including 404s and 500s.
Ready to test yourself?
Practice Express— quiz & coding exercises