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
php
use Illuminate\Support\Facades\Route; use App\Http\Controllers\Admin\DashboardController; use App\Http\Controllers\Admin\UserController; use App\Http\Controllers\Admin\ReportController;
How nested route groups compose in Laravel
routing
middleware
authorization
Intermediate
8 steps
javascript
import { useRef, useCallback, useEffect, useState } from "react"; function useThrottle(callback, delay) { const lastRun = useRef(0);
Building a throttle hook in React
throttling
custom-hooks
refs
Intermediate
8 steps
go
package middleware import ( "bytes"
Verifying webhook HMAC signatures in Gin
hmac
middleware
webhooks
Intermediate
7 steps
javascript
async function copyToClipboard(text) { if (navigator.clipboard && window.isSecureContext) { try { await navigator.clipboard.writeText(text);
Copying to the clipboard with a fallback
clipboard
progressive-enhancement
dom
Intermediate
8 steps
javascript
import { useEffect, useRef, useState } from "react"; export function Dropdown({ label, children }) { const [open, setOpen] = useState(false);
Closing a dropdown on outside click in React
outside-click
event-listeners
cleanup
Intermediate
8 steps
javascript
'use server' import { z } from 'zod' import { redirect } from 'next/navigation'
How a Next.js Server Action validates a form
server-actions
form-validation
zod
Intermediate
7 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.