Tutorial · Web application security · Express
Security headers and CSP – nonces, strict-dynamic, report-only, HSTS, Permissions-Policy and CORS in Express, NestJS and CloudFront
We configure the pierogi store's security headers – a Content Security Policy with nonces and strict-dynamic rolled out in report-only mode first, HSTS with preload, protection against framing, Referrer-Policy, Permissions-Policy and CORS without the "star". Helmet in Express and NestJS, a CloudFront headers policy for a static SPA, real header dumps, an interactive CSP builder and testing tools.
After the penetration test, the pierogi store fixed every XSS-prone spot that was found. The auditor asked, though: "And what if someone adds a new one tomorrow?". Security headers are the second line of defence: the browser itself refuses to run a script you didn't authorize, to embed the page in someone else's frame or to connect over HTTP – even when the code has a bug. In this tutorial we configure them in Express, NestJS and CloudFront, roll out a CSP without breaking production and verify the result.
Prerequisites: Express or NestJS (Express tutorial, NestJS tutorial), HTTP basics and the browser's same-origin policy. It's worth reading OWASP Top 10 in practice first.
- 128 bits
- of nonce randomness – new in every response
- ≥ 1 year
- HSTS max-age – required for the preload list
- 0
- X-XSS-Protection – the old browser filter – switched off
- 2 steps
- CSP rollout – report-only, then enforcement
The header map
| Header | What it protects against | Recommended value |
|---|---|---|
Content-Security-Policy | the impact of XSS, loading resources from foreign hosts, clickjacking (frame-ancestors) | a strict CSP with a nonce (below) |
Strict-Transport-Security | traffic interception, downgrade to HTTP | max-age=63072000; includeSubDomains; preload (once prepared) |
X-Content-Type-Options | MIME sniffing (e.g. an "image" that is really a script) | nosniff |
X-Frame-Options | clickjacking in older browsers | DENY (twin of frame-ancestors 'none') |
Referrer-Policy | leaking URL paths and parameters to other sites | strict-origin-when-cross-origin or no-referrer |
Permissions-Policy | abuse of browser APIs by scripts and frames | camera=(), microphone=(), geolocation=(self) |
Cross-Origin-Opener-Policy | access to your window from windows opened by other sites | same-origin |
Cross-Origin-Resource-Policy | embedding of your resources by foreign sites | same-origin or same-site |
X-XSS-Protection | nothing – the old filter was itself a source of vulnerabilities | 0 |
CSP from scratch
A Content Security Policy is a list of directives telling the browser where the page may load scripts, styles, images, connections and frames from. Scripts are what matters most – and there are three approaches:
- A host allowlist (
script-src 'self' https://cdn.example) – easy but weak: Google's research showed that most such policies can be bypassed through allowed hosts that serve JSONP or old libraries. - A strict CSP with a nonce:
script-src 'nonce-R4nd0m' 'strict-dynamic'. Only a script whosenonceattribute equals the value from this particular response's header runs, andstrict-dynamicpasses trust on to scripts it loads itself. An attacker who injects a<script>doesn't know the nonce. - A strict CSP with hashes – for static pages where you can't inject a nonce per response:
script-src 'sha256-…'for each inline script. A static SPA with no inline scripts (a typical Vite build) can simply usescript-src 'self'.
https: and 'unsafe-inline' in a strict CSP are only a fallback for very old browsers – modern ones ignore them when they see a nonce and strict-dynamic. Always add object-src 'none' and base-uri 'none' (without them script-src can be bypassed) and frame-ancestors.
Content-Security-Policy header builder – Toggle options and read the notes – a starting point, not a replacement for testing in a browser.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>CSP builder</title>
</head>
<body>
<form id="form">
<fieldset>
<legend>Scripts</legend>
<label><input type="radio" name="scripts" value="strict" checked /> nonce + 'strict-dynamic' (recommended)</label>
<label><input type="radio" name="scripts" value="self" /> 'self' only (static SPA)</label>
<label><input type="radio" name="scripts" value="unsafe" /> 'self' 'unsafe-inline' (weak)</label>
</fieldset>
<label>Extra image hosts <input name="img" value="https://media.pierogarnia.example" /></label>
<label>Extra API hosts (connect-src) <input name="connect" placeholder="https://api.pierogarnia.example" /></label>
<div class="checks">
<label><input type="checkbox" name="object" checked /> object-src 'none'</label>
<label><input type="checkbox" name="base" checked /> base-uri 'none'</label>
<label><input type="checkbox" name="frames" checked /> frame-ancestors 'none'</label>
<label><input type="checkbox" name="upgrade" checked /> upgrade-insecure-requests</label>
<label><input type="checkbox" name="report" /> reports (report-to)</label>
<label><input type="checkbox" name="reportOnly" /> report only (Report-Only)</label>
</div>
</form>
<h3>Header</h3>
<pre id="header"></pre>
<h3>Notes</h3>
<ul id="warnings"></ul>
<script src="index.js"></script>
</body>
</html>import "./styles.css";
const T = {
unsafe: "'unsafe-inline' lets any injected inline script run – the CSP barely protects against XSS.",
object: "No object-src 'none' – legacy plugins (<object>, <embed>) can bypass script-src.",
base: "No base-uri – an injected <base href> can redirect relative script URLs.",
frames: "No frame-ancestors – the page can be embedded in someone else's frame (clickjacking).",
reportOnly: "Report-Only mode blocks nothing – it's a rollout stage, not the end state.",
report: "Without reports you won't know what the policy blocks for real users.",
ok: "Looks good. Remember: the nonce must be random in every response.",
};
const form = document.getElementById("form");
function build() {
const f = Object.fromEntries(new FormData(form));
const scripts = {
strict: "'nonce-R4nd0mPerResponse' 'strict-dynamic' https: 'unsafe-inline'",
self: "'self'",
unsafe: "'self' 'unsafe-inline'",
}[f.scripts];
const d = [["default-src", "'self'"], ["script-src", scripts]];
d.push(["img-src", `'self' data: ${f.img}`.trim()]);
d.push(["connect-src", `'self' ${f.connect}`.trim()]);
if (f.object) d.push(["object-src", "'none'"]);
if (f.base) d.push(["base-uri", "'none'"]);
if (f.frames) d.push(["frame-ancestors", "'none'"]);
if (f.upgrade) d.push(["upgrade-insecure-requests"]);
if (f.report) d.push(["report-to", "csp"]);
const name = f.reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
document.getElementById("header").textContent = `${name}: ${d.map((x) => x.join(" ")).join("; ")}`;
const notes = [];
if (f.scripts === "unsafe") notes.push(T.unsafe);
if (!f.object) notes.push(T.object);
if (!f.base) notes.push(T.base);
if (!f.frames) notes.push(T.frames);
if (f.reportOnly) notes.push(T.reportOnly);
if (!f.report) notes.push(T.report);
const items = (notes.length ? notes : [T.ok]).map((text) => Object.assign(document.createElement("li"), { textContent: text }));
document.getElementById("warnings").replaceChildren(...items);
}
form.addEventListener("input", build);
build();body { font-family: system-ui, sans-serif; margin: 0; padding: 16px; color: #1f2328; font-size: 14px; }
form { display: grid; gap: 10px; max-width: 680px; }
fieldset { border: 1px solid #d0d7de; border-radius: 8px; display: grid; gap: 4px; }
input[name="img"], input[name="connect"] { width: 100%; box-sizing: border-box; padding: 6px; font: 12px ui-monospace, monospace; }
.checks { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 4px; }
pre { background: #f6f8fa; padding: 10px; border-radius: 8px; white-space: pre-wrap; word-break: break-all; font-size: 12px; }
h3 { margin: 12px 0 4px; font-size: 14px; }
li { margin: 4px 0; }Step 1. Express and helmet
npm install helmet cors pino
Security headers in Express (helmet, CORS, a nonce for the SPA)
import type { Express, Response } from 'express';
import cors from 'cors';
import helmet from 'helmet';
import { randomBytes } from 'node:crypto';
export function securityHeaders(app: Express, opts: { reportOnly?: boolean } = {}) {
// A fresh, unpredictable nonce for every HTML response.
app.use((_req, res, next) => {
res.locals.cspNonce = randomBytes(16).toString('base64');
next();
});
app.use(helmet({
contentSecurityPolicy: {
useDefaults: false,
reportOnly: opts.reportOnly, // roll out as Content-Security-Policy-Report-Only first
directives: {
defaultSrc: ["'self'"],
// Strict CSP: only scripts carrying our nonce, plus what they load ('strict-dynamic').
// https: and 'unsafe-inline' are fallbacks for old browsers – modern ones ignore them.
scriptSrc: [(_req, res) => `'nonce-${(res as Response).locals.cspNonce}'`, "'strict-dynamic'", 'https:', "'unsafe-inline'"],
styleSrc: ["'self'"],
imgSrc: ["'self'", 'data:', 'https://media.pierogarnia.example'],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
baseUri: ["'none'"],
formAction: ["'self'"],
frameAncestors: ["'none'"], // nobody may frame us (clickjacking)
upgradeInsecureRequests: [],
reportUri: ['/csp-reports'], // widely supported
reportTo: ['csp'], // Reporting API, endpoint defined below
},
},
strictTransportSecurity: { maxAge: 63_072_000, includeSubDomains: true, preload: true }, // 2 years
referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
xFrameOptions: { action: 'deny' }, // legacy twin of frame-ancestors 'none'
}));
// Headers helmet doesn't set.
app.use((_req, res, next) => {
res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=(self), usb=()');
res.setHeader('Reporting-Endpoints', 'csp="https://pierogarnia.example/csp-reports"');
next();
});
// CORS only for the API and only for our own front-ends – never "*" with credentials.
app.use('/api', cors({
origin: ['https://pierogarnia.example', 'https://admin.pierogarnia.example'],
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 600,
}));
}import express from 'express';
import { readFileSync } from 'node:fs';
import { pino } from 'pino';
import { securityHeaders } from './security-headers.js';
const log = pino();
const app = express();
securityHeaders(app, { reportOnly: process.env.CSP_REPORT_ONLY === 'true' });
// CSP violation reports: the classic format (report-uri) and the Reporting API (report-to).
app.post('/csp-reports', express.json({ type: ['application/csp-report', 'application/reports+json'], limit: '20kb' }), (req, res) => {
log.warn({ csp: req.body }, 'csp violation');
res.sendStatus(204);
});
app.get('/api/menu', (_req, res) => { res.json([{ name: 'Ruskie', price: 32 }]); });
// The SPA shell: every <script> gets this response's nonce. Don't let a CDN cache this HTML.
const indexHtml = readFileSync(new URL('../public/index.html', import.meta.url), 'utf8');
app.get(/^\/(?!api\/).*/, (_req, res) => {
res.set('Cache-Control', 'no-store')
.type('html')
.send(indexHtml.replaceAll('<script', `<script nonce="${res.locals.cspNonce}"`));
});
app.listen(3006, () => log.info('http://localhost:3006'));<!doctype html>
<html lang="pl">
<head><meta charset="utf-8" /><title>Pierogarnia</title></head>
<body><div id="root"></div><script type="module" src="/assets/index-4f2a9c.js"></script></body>
</html>The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Step 2. Rollout: report-only first
- HSTS and the preload list
- Frames, referrer, permissions and isolation
- CORS done right
- Step 3. NestJS
- Step 4. CloudFront for a static SPA
- How to test
- Common mistakes
- Test yourself
- What's next