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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A middleware factory lets you bake configuration into a closure once and reuse the returned handler on every request.
- 2A fresh per-request CSP nonce lets you allow specific inline scripts without opening the door to arbitrary ones.
- 3Some headers should be conditional — send HSTS only over HTTPS so you never lock clients into a broken policy.
Related explainers
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-configurable-security-headers-middleware-in-express-explained-javascript-0c3d/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.