Difficulty: Advanced
What is Content Security Policy (CSP), and how does it reduce the impact of XSS? How would you deploy a strict CSP on a real site?
Content Security Policy is an HTTP response header (Content-Security-Policy) that tells the browser which sources of scripts, styles, images, frames and other resources a page may load and execute. If an attacker manages to inject a <script> tag or an inline event handler, a strict CSP stops the browser from running it, turning many XSS bugs into harmless broken markup. CSP is a defence-in-depth layer: it reduces the impact of XSS, but you still need output encoding and safe templating.
The browser enforces directives such as:
script-src: where JavaScript may come from. Without 'unsafe-inline', inline <script> blocks and onclick= handlers are blocked.'unsafe-eval' absent: eval(), new Function() and string setTimeout are blocked.object-src 'none': blocks legacy plugin content.base-uri 'none': stops an injected <base> tag from redirecting relative script URLs.frame-ancestors: controls who may frame your page (clickjacking protection, replaces X-Frame-Options).So if a comment field renders <img src=x onerror=alert(1)>, the inline handler simply does not run.
| Approach | Example | Weakness |
|---|---|---|
| Host allowlist | script-src 'self' cdn.example.com | Bypassable if any allowed host serves JSONP or an old Angular build; long lists are hard to maintain |
| Nonce-based | script-src 'nonce-r4nd0m' 'strict-dynamic' | Nonce must be random per response; needs server rendering support |
| Hash-based | script-src 'sha256-...' | Good for static pages; every inline script change needs a new hash |
Current guidance (Google, OWASP) favours a strict CSP: a fresh random nonce on every response, added as the nonce attribute on each legitimate script tag, plus 'strict-dynamic' so scripts you trust can load their own dependencies. Injected scripts do not know the nonce, so they are blocked. In CSP Level 3 browsers, when a nonce or hash is present, 'unsafe-inline' is ignored, so you can include it as a fallback for very old browsers.
Content-Security-Policy-Report-Only with a report-to (or legacy report-uri) endpoint.eval.require-trusted-types-for 'script' to lock down DOM XSS sinks like innerHTML.frame-ancestors, report-uri and sandbox do not work in a <meta http-equiv> CSP; send a real header.'strict-dynamic' helps a lot here.import crypto from "node:crypto";
import express from "express";
const app = express();
app.use((req, res, next) => {
// 128 bits of randomness, new for every response
res.locals.nonce = crypto.randomBytes(16).toString("base64");
res.setHeader(
"Content-Security-Policy",
[
`script-src 'nonce-${res.locals.nonce}' 'strict-dynamic' https: 'unsafe-inline'`,
"object-src 'none'",
"base-uri 'none'",
"frame-ancestors 'self'",
"report-to csp",
].join("; ")
);
res.setHeader("Reporting-Endpoints", 'csp="https://example.com/csp-reports"');
next();
});
app.get("/", (req, res) => {
res.send(`<script nonce="${res.locals.nonce}" src="/app.js"></script>`);
});
Modern browsers use the nonce and strict-dynamic and ignore https: and 'unsafe-inline', which exist only as fallbacks for old browsers. The nonce changes on every request so an attacker cannot predict it.
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Security-Policy-Report-Only: script-src 'nonce-Q2hhbmdlTWU=' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp
Reporting-Endpoints: csp="https://example.com/csp-reports"
Report-only mode logs what would be blocked without blocking it, so you can fix violations before enforcing.
Content Security Policy, XSS, Nonce-based CSP, strict-dynamic, Trusted Types, Security Headers