javascript 46 lines · 7 steps

A configurable security-headers middleware in Express

A factory function returns Express middleware that sets a per-request CSP nonce plus a full suite of hardening headers.

Explained by highlit
1const crypto = require('crypto');
2 
3function securityHeaders(options = {}) {
4 const {
5 hsts = true,
6 maxAge = 15552000,
7 reportUri = null,
8 } = options;
9 
10 return function (req, res, next) {
11 const nonce = crypto.randomBytes(16).toString('base64');
12 res.locals.cspNonce = nonce;
13 
14 const directives = [
15 "default-src 'self'",
16 `script-src 'self' 'nonce-${nonce}'`,
17 "style-src 'self' 'unsafe-inline'",
18 "img-src 'self' data:",
19 "object-src 'none'",
20 "base-uri 'self'",
21 "frame-ancestors 'none'",
22 ];
23 if (reportUri) directives.push(`report-uri ${reportUri}`);
24 
25 res.setHeader('Content-Security-Policy', directives.join('; '));
26 res.setHeader('X-Content-Type-Options', 'nosniff');
27 res.setHeader('X-Frame-Options', 'DENY');
28 res.setHeader('Referrer-Policy', 'no-referrer');
29 res.setHeader('Cross-Origin-Opener-Policy', 'same-origin');
30 res.setHeader('Cross-Origin-Resource-Policy', 'same-origin');
31 res.setHeader('Permissions-Policy', 'geolocation=(), camera=(), microphone=()');
32 res.setHeader('X-DNS-Prefetch-Control', 'off');
33 
34 if (hsts && req.secure) {
35 res.setHeader(
36 'Strict-Transport-Security',
37 `max-age=${maxAge}; includeSubDomains; preload`
38 );
39 }
40 
41 res.removeHeader('X-Powered-By');
42 next();
43 };
44}
45 
46module.exports = securityHeaders;
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A middleware factory lets you bake configuration into a closure once and reuse the returned handler on every request.
  2. 2A fresh per-request CSP nonce lets you allow specific inline scripts without opening the door to arbitrary ones.
  3. 3Some headers should be conditional — send HSTS only over HTTPS so you never lock clients into a broken policy.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A configurable security-headers middleware in Express — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code