← blog · November 10, 2026

Deploying Content Security Policy Without Breaking Your Site: Nonces, strict-dynamic, Hashes and Report-Only

Why host-allowlist CSPs are easy to bypass, how to build a nonce plus strict-dynamic policy, how to trial it in report-only mode, and the pitfalls, like cached nonces, that silently remove the protection.

Content Security Policy is the most effective browser mechanism for making an XSS bug hard to exploit. Yet most policies found in the wild either block nothing or break the site on the first deploy and get rolled back in a hurry. The first failure usually comes from a long host allowlist with 'unsafe-inline' tacked on; the second from enforcing a policy that was never tested against real traffic. This post covers how to build a policy that actually holds and how to ship it without breaking anything.

What CSP protects, and what it does not

CSP does not fix an injection bug. When an attacker manages to inject markup, CSP tries to stop the browser from executing the script inside it. It is a second line of defence: escaping and output encoding still have to be right. Keep that distinction clear, because teams that treat CSP as "the XSS fix" tend to loosen their escaping.

Almost all of the value sits in script-src. Directives like img-src and font-src make exfiltration slightly harder, but controlling script execution is the real win.

Three approaches

Host allowlist. Something like script-src 'self' https://cdn.example.com https://analytics.example.com. It is the intuitive option and the weakest. If any allowed host serves a JSONP endpoint, user-uploaded content, or an old template library, the attacker loads their payload from that host and the policy waves it through. Listing a large shared CDN means trusting every file on it. Google's large-scale study of deployed policies found that the vast majority of allowlist-based ones could be bypassed this way.

Nonce-based policy. The server generates an unpredictable value per response and writes it into both the header and every legitimate <script> tag. The browser runs only scripts carrying that value. Injected markup cannot know the nonce, so it does not run.

Hash-based policy. The SHA-256 digest of an inline script's content goes into the policy, and the script runs as long as its content is unchanged. No per-request generation is needed, which makes it the right choice for static sites and cached HTML.

Our position: any application that renders HTML on the server should use a nonce combined with 'strict-dynamic'. Pages that are served statically or cached at a CDN should use hashes. Keep host lists only as a fallback for old browsers.

A recommended policy

Content-Security-Policy:
  script-src 'nonce-R4nd0mBase64Value' 'strict-dynamic' https: 'unsafe-inline';
  object-src 'none';
  base-uri 'none';
  report-to csp-endpoint

The real header is a single line; it is split here for readability. Why each part is there:

  • 'strict-dynamic' lets a nonced script pass trust on to the scripts it creates, so tag managers and module loaders work without being listed one by one. Browsers that understand it ignore host sources and 'unsafe-inline' in the same policy.
  • https: and 'unsafe-inline' exist only for older browsers. A browser that understands nonces already ignores 'unsafe-inline', and one that understands 'strict-dynamic' ignores https:. They do not weaken the policy in modern browsers and they keep old ones working.
  • object-src 'none' closes the plugin-based route to script execution.
  • base-uri 'none' is the line people forget: an injected <base> tag can redirect nonced scripts loaded by relative path to an attacker's server.

Nonce generation belongs in the application. A minimal Node.js example:

import crypto from "node:crypto";

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString("base64");
  res.locals.cspNonce = nonce;
  res.setHeader(
    "Content-Security-Policy",
    `script-src 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'; ` +
    `object-src 'none'; base-uri 'none'`
  );
  next();
});

Templates then emit <script nonce="<%= cspNonce %>">. For a static inline script, compute the hash like this:

printf '%s' 'console.log("hello")' | openssl dgst -sha256 -binary | openssl base64

The result goes into the policy as 'sha256-<value>'. The digest covers the exact bytes between the tags, so a leading space or a different line ending changes it.

Shipping it without breaking the site

Send the policy first as Content-Security-Policy-Report-Only. The browser blocks nothing under that header and only reports violations. Both headers can be sent at once, so you can keep enforcing your current loose policy while observing the strict one.

The old report-uri directive is still widely supported; the newer path is defining an endpoint with the Reporting-Endpoints header and referencing it with report-to. Sending both during the transition is safe. Adding 'report-sample' to script-src makes reports include the first characters of the blocked inline code, which makes finding the offending script far easier.

Decide the observation period by traffic, not by calendar. Rarely visited screens such as checkout, admin pages and error pages need to be hit before you enforce, otherwise the first person to find the breakage is a customer.

Pitfalls

Cached nonces. If nonced HTML gets cached by a CDN or reverse proxy, every visitor receives the same nonce. The value is no longer secret and the protection silently disappears. Keep nonced pages out of shared caches, or switch those pages to hashes.

Inline event handlers. Attributes like onclick="..." cannot carry a nonce and will not run under a strict policy. They have to be rewritten with addEventListener. There is an escape hatch called 'unsafe-hashes', but treat it as a migration aid, not a destination. In an older front end this rewrite is usually the largest piece of work.

javascript: URLs. href="javascript:..." is blocked for the same reason and accounts for a fair share of violations with no obvious source.

Extension noise. Browser extensions inject scripts into pages and your report endpoint fills up with them. Group reports by source scheme and document path and separate out things like chrome-extension, or real breakage drowns in the noise.

Limits of the <meta> tag. A policy can be delivered with <meta http-equiv>, but frame-ancestors, reporting and report-only mode do not work that way. Send it as a response header.

Multiple policies. When a response carries two CSP headers, the browser enforces both, and a resource loads only if it passes each of them. That is usually the answer when the application sets one header, the reverse proxy adds another, and nobody can explain why something is blocked. Make sure the policy is owned in exactly one place.

Starting with style-src. Because of style attributes and styles injected at runtime by frameworks, a strict style-src is a big project in most applications, and the security gain is small compared to script-src. Lock down scripts first and leave styles for later.

When not to take this route

If every page is served cached from a CDN and inline scripts vary, nonces fight your architecture. Moving inline scripts into external files and relying on 'self' plus hashes is more sustainable there.

If you load a third-party widget from a source you do not control, 'strict-dynamic' means trusting everything that widget loads. That can be an acceptable trade-off, but make it deliberately.

Finally, do not treat CSP as a header you write once and forget. A new analytics tool, a new payment provider or a framework upgrade can break it. Keeping the report endpoint permanent and tracking violation counts as a metric is the cheapest way to see breakage before your customers do.