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
javascript
import { Suspense } from 'react'; import { searchProducts } from '@/lib/products'; import SearchInput from './search-input';
Streaming search results in a Next.js Server Component
server-components
suspense
streaming
Intermediate
8 steps
rust
use axum::{ body::{Body, Bytes}, extract::Request, http::StatusCode,
Logging request and response sizes in Axum
middleware
http
streaming-bodies
Advanced
8 steps
javascript
import { useState } from 'react'; function StarRating({ value = 0, max = 5, onChange, size = 24 }) { const [hovered, setHovered] = useState(null);
Building an accessible star rating in React
controlled-component
accessibility
state-management
Intermediate
8 steps
go
package handler type flightResult struct { status int
Deduping in-flight requests in Gin
middleware
concurrency
deduplication
Advanced
9 steps
javascript
import { notFound } from 'next/navigation' import { Suspense } from 'react' import { getPostBySlug, getRelatedPosts } from '@/lib/posts' import { RelatedPosts } from '@/components/related-posts'
Building a dynamic blog post page in Next.js
server-components
dynamic-routing
metadata
Intermediate
8 steps
rust
use once_cell::sync::Lazy; use regex::Regex; static CREDIT_CARD: Lazy<Regex> = Lazy::new(|| {
Redacting sensitive data from logs in Rust
regex
lazy-initialization
checksum-validation
Intermediate
9 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.