LeepCast
Subscribe
All posts
Security

Strict Content Security Policy: How Nonces and strict-dynamic Stop XSS

Domain allowlist CSPs are routinely bypassed. This guide explains how a nonce- or hash-based strict CSP with 'strict-dynamic' works, what it breaks, and how to roll it out safely with report-only mode.

LeepCast7 min read
Strict Content Security Policy: How Nonces and strict-dynamic Stop XSS

Cross-site scripting is still one of the most common ways web applications get compromised. Output encoding and careful templating are the first line of defence, but a single missed escape is enough to let an attacker run script in a victim's session. Content Security Policy (CSP) is the browser-enforced second line: an HTTP response header that tells the browser which scripts it may execute, so that injected markup stays inert even when an escaping bug slips through.

Many teams already send a CSP header and assume they are protected. Often they are not. This explainer covers why the classic domain-allowlist style of policy tends to fail, how the nonce-based "strict CSP" recommended by Google's web. dev guidance works, what each directive in it is for, and how to roll it out without breaking a production site.

Why allowlist policies rarely stop XSS

The intuitive way to write a CSP is to list the places scripts may come from: your own origin, a CDN, an analytics provider, a tag manager. The trouble is that a policy like this trusts entire hosts, and popular hosts serve far more than the one file you wanted. If any allowlisted origin hosts a JSONP endpoint, an old copy of a framework that evaluates templates, or user-uploaded files, an attacker who can inject a script tag can point it at that content and the browser will happily run it.

The web. dev guidance on strict CSP puts it plainly: allowlist policies need extensive customization and can be bypassed in most configurations. They also grow over time as marketing and product teams add vendors, so the attack surface expands with every new entry. A strict CSP sidesteps the problem by not trusting URLs at all. Instead, it trusts individual script elements that the server has explicitly marked.

The recommended strict policy

For pages rendered on the server, web. dev recommends this shape of policy, where the nonce is a fresh random value for every response:

script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none';

— web. dev, Mitigate cross-site scripting with a strict CSP

Every script tag the server intends to run carries a matching nonce attribute. Anything without that value, including a script tag an attacker managed to inject, is refused. Because the attacker cannot predict a random value that changes on every page load, they cannot forge a valid tag. Each part of the policy has a specific job:

  • 'nonce-{RANDOM}' allows only script elements whose nonce attribute matches this value. MDN advises at least 128 bits from a cryptographically secure random generator, base64-encoded, and a new value for every response.
  • 'strict-dynamic' propagates trust: a script that was allowed by its nonce or hash may load further scripts by creating script elements, and those run too. This is what lets bundlers, loaders and many third-party widgets keep working. When it is present, CSP Level 3 browsers ignore host allowlists, 'self' and 'unsafe-inline' for scripts.
  • object-src 'none' disables plugin content such as embedded objects, which has historically been a way to run code outside the script policy.
  • base-uri 'none' blocks injected base tags. Without it, an attacker could insert a base element that silently redirects every relative script URL on the page to their own server.

Fallbacks for older browsers

The same guidance suggests appending https: and 'unsafe-inline' to script-src. This looks alarming but is safe by design. Browsers that understand 'strict-dynamic' ignore both of them. Browsers that understand nonces but not 'strict-dynamic' ignore 'unsafe-inline' when a nonce is present and fall back to allowing HTTPS scripts. Only very old browsers that support neither feature use 'unsafe-inline', which leaves them no worse off than having no policy at all. MDN describes this layering explicitly: one header behaves like a CSP1, CSP2 or CSP3 policy depending on what the browser supports.

A minimal working example

The server below, written with only Node. js built-ins, generates a nonce per request, sends the full fallback-compatible strict policy, and embeds the same nonce in its one inline script. It uses report-only mode, discussed in the rollout section, so nothing is blocked yet. Save it as server. mjs and run it with Node 18 or newer.

javascript
// server.mjs -- run with: node server.mjs, then open http://localhost:8080
import http from "node:http";
import crypto from "node:crypto";

const server = http.createServer((req, res) => {
  // 16 random bytes = 128 bits, fresh for every response
  const nonce = crypto.randomBytes(16).toString("base64");

  const policy = [
    `script-src 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'`,
    "object-src 'none'",
    "base-uri 'none'",
    "report-to csp-endpoint",
  ].join("; ");

  res.setHeader("Reporting-Endpoints", 'csp-endpoint="https://example.com/csp-reports"');
  res.setHeader("Content-Security-Policy-Report-Only", policy);
  res.setHeader("Cache-Control", "no-store");
  res.setHeader("Content-Type", "text/html; charset=utf-8");

  res.end(`<!doctype html>
<html>
  <body>
    <button id="save">Save</button>
    <script nonce="${nonce}">
      document.getElementById("save").addEventListener("click", () => {
        console.log("saved");
      });
    </script>
  </body>
</html>`);
});

server.listen(8080);

Two details matter here. First, the nonce is created inside the request handler, never at startup, so every response gets a different value. Second, the page is marked Cache-Control: no-store. If a shared cache or CDN stored this HTML, every visitor would receive the same nonce, and a nonce that is reused is a nonce that can be learned. For pages that must be cached, the hash-based variant described below is the better fit.

What a strict CSP breaks, and how to fix it

Turning on a strict policy reveals every place where the application relies on inline code that the server never marked as trusted. The common categories are predictable:

  1. Inline event handler attributes such as onclick or onload. Nonces cannot be attached to attributes, so these are blocked. Move the logic into a nonced script and register listeners with addEventListener.
  2. javascript: URLs in links and form actions. Replace them with real URLs plus a script-registered click handler.
  3. Script tags rendered by templates or CMS fragments that never received the nonce. Every server-side code path that emits a script tag needs access to the per-request value.
  4. Use of eval and similar string-to-code functions. These are blocked unless 'unsafe-eval' is added; web. dev recommends replacing eval with JSON. parse where it is only being used to read data.

The inline-handler refactor is usually the largest piece of work, but it is mechanical. Here is the typical before and after, where {{NONCE}} stands for the per-request value the server template fills in:

html
<!-- Before: blocked by a strict CSP -->
<button onclick="save()">Save</button>
<a href="javascript:openHelp()">Help</a>

<!-- After: same behaviour, no inline handlers -->
<button id="save">Save</button>
<a href="/help" id="help">Help</a>
<script nonce="{{NONCE}}">
  document.getElementById("save").addEventListener("click", save);
  document.getElementById("help").addEventListener("click", (event) => {
    event.preventDefault();
    openHelp();
  });
</script>

If a third-party library injects its own inline handlers that cannot be changed, CSP Level 3 offers 'unsafe-hashes', which allows specific event-handler bodies by their hash. It is a narrow escape hatch rather than a general solution, and each use deserves a comment explaining why it exists.

Hash-based CSP for static and cached pages

Static sites and heavily cached pages cannot easily produce a new nonce per response. For them, the alternative is to list the SHA-256 hash of each inline script in the policy, in the form script-src 'sha256-{HASH}' 'strict-dynamic'; object-src 'none'; base-uri 'none'. The browser hashes each inline script it encounters and runs it only if the result is in the list. Combined with 'strict-dynamic', a small hashed inline loader can then add external scripts dynamically.

The hash covers the exact text between the opening and closing script tags. MDN notes that capitalization and whitespace matter, including leading and trailing whitespace, so a reformatted script silently stops matching. Hashes are best generated by the build step rather than by hand. For a quick check, the hash can be computed from the command line:

bash
# Hash of the exact script body (no <script> tags; whitespace matters)
printf '%s' 'console.log("hi")' | openssl dgst -sha256 -binary | openssl base64

Chrome DevTools also prints the expected hash in the console when an inline script is blocked, which helps when debugging a mismatch.

Rolling it out safely

Deploying an enforcing policy directly to production is a reliable way to break checkout pages and analytics. The safer path uses the Content-Security-Policy-Report-Only header, which evaluates the policy and reports violations without blocking anything.

  1. Add nonces to every script tag the server renders, and refactor inline handlers and javascript: URLs.
  2. Send the policy in Content-Security-Policy-Report-Only with a report-to directive pointing at an endpoint declared in a Reporting-Endpoints header. MDN notes that report-only mode has no effect without a reporting directive, and that report-uri is deprecated but still worth sending alongside report-to while browser support for report-to is incomplete.
  3. Collect reports from real traffic for long enough to cover rarely used pages, then fix or explicitly accept each distinct violation.
  4. Switch the header name to Content-Security-Policy to enforce, keeping reporting enabled so regressions surface quickly.
  5. Check the final policy with Google's CSP Evaluator or Lighthouse, both of which flag weak configurations.

Report-only mode has one notable limitation: it cannot be delivered through an HTML meta tag. It must be sent as a real HTTP response header, which means the server, framework middleware or CDN configuration has to be involved from the start.

Pitfalls worth knowing

  • Never reuse a nonce across responses or users, and never derive it from anything predictable such as a timestamp or session ID.
  • Do not copy the nonce into places an attacker can read. Browsers hide the nonce content attribute from getAttribute and expose it only through the element's nonce property, specifically to stop injected CSS selectors from leaking it.
  • Do not let user input decide whether a script tag gets a nonce. Any template path that nonces attacker-influenced markup undoes the protection.
  • Remember that CSP is defence in depth. It reduces the impact of an injection bug; it does not replace contextual output encoding or input handling.

The takeaway

A strict CSP is short: a per-response nonce or a set of hashes, 'strict-dynamic', object-src 'none' and base-uri 'none'. Its strength comes from trusting specific script elements instead of whole domains, which removes the bypass routes that make allowlist policies fragile. The real effort lies in refactoring inline handlers and plumbing the nonce through templates, and report-only mode makes it possible to do that work against real traffic before anything is enforced.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments