Content Security Policy Explained: Nonces, strict-dynamic and Report-Only
A content security policy is an HTTP header that tells the browser which scripts, styles, images and other resources a page may load. Done well, it stops most cross-site scripting attacks even when an injection bug slips through. We served eight test pages with different policies to a real Chromium browser and recorded exactly what was blocked and what ran.
- A content security policy is sent as the
Content-Security-Policyresponse header; the browser enforces it on every resource the page loads. - With a nonce-based policy, the inline script carrying the right nonce ran and an identical script without it was blocked.
- Adding
'strict-dynamic'let our trusted script load another script; without it, the same loader was blocked. Content-Security-Policy-Report-Onlyreported the violation but let the script run, which is how you test a policy safely.
Cross-site scripting (XSS) happens when an attacker gets their own JavaScript into your page, through a comment field, a URL parameter or a third-party widget. Input escaping is the first defence, but one missed spot is enough. A content security policy (CSP) is a second layer: even if malicious markup reaches the page, the browser refuses to run code that the policy did not approve.
To see the rules in action rather than just describe them, we wrote a tiny Python server that sends eight pages, each with a different policy, and loaded them in a Chromium-based browser. Each page listened for the securitypolicyviolation event and printed what was blocked. The results below are from that run.
What is a content security policy?
CSP is a W3C standard supported by all modern browsers. The server lists trusted sources for each type of resource (scripts, styles, images, fonts, frames, network connections), and the browser blocks everything else, logging a violation. It does not replace secure coding; it limits the damage when something goes wrong, much as HttpOnly cookies limit what a stolen script could read.
How the header works
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self' https://cdn.example.com
A policy is a list of directives separated by semicolons. Each directive names a resource type and its allowed sources: 'self' (same origin), specific hosts, https:, 'none', or keywords such as 'nonce-...' and 'strict-dynamic'. default-src is the fallback for any type you do not list. Keywords must be in single quotes; host names must not.
Our test setup
n = secrets.token_urlsafe(16) # a fresh nonce for every response
self.send_header("Content-Security-Policy", policy.format(n=n))
# in every page, a nonced listener:
document.addEventListener("securitypolicyviolation",
e => R.push("blocked " + e.effectiveDirective + " " + (e.blockedURI || "")));
The server generated a new random nonce per response, as a real application must. The violation listener is a useful debugging tool in its own right: it shows the exact directive responsible for each block.
Test 1: inline scripts are blocked
Policy: script-src 'self' 'nonce-...'
Page: <script>out.textContent = "inline script RAN"</script>
Result: inline script did not run
blocked script-src-elem inline
Once a policy has a script-src without 'unsafe-inline', inline <script> blocks and inline event handlers such as onclick stop working. This is the main protection: most XSS payloads are inline scripts. It is also the main source of breakage when adding CSP to an old site, so expect to move inline code into files or give it a nonce.
Test 2: nonces approve specific scripts
Policy: script-src 'nonce-...'
Page: <script nonce="...">...</script> and <script>document.title = ...</script>
Result: nonced script RAN
blocked script-src-elem inline (the second script)
A nonce is a random, single-use value placed both in the header and on each trusted script tag. The browser runs a script only if its nonce attribute matches. An attacker injecting markup cannot guess the value, because it changes on every page load. The nonce must be unpredictable (at least 128 bits from a secure random generator) and must never be reused or cached in a shared page. For static sites where you cannot generate nonces per response, use hashes instead: 'sha256-...' of each inline script’s exact content.
Test 3: strict-dynamic trusts scripts loaded by trusted scripts
Policy: script-src 'nonce-...' 'strict-dynamic'; object-src 'none'; base-uri 'none'
Page: nonced script creates <script src="/lib.js"> and appends it
Result: script loaded by trusted script RAN
no violations
Real applications load scripts dynamically: tag managers, analytics, code splitting. Giving each of those a nonce is impractical. 'strict-dynamic' passes trust on: any script created by an already-trusted script is allowed too. This is the policy recommended by Google’s web.dev strict CSP guide. With 'strict-dynamic' present, browsers that support it ignore host allowlists and 'self' for scripts, so the nonce becomes the only way in for parser-inserted scripts; we did not run a separate test for that rule.
Test 4: without strict-dynamic, loaders break
Policy: script-src 'self' 'nonce-...'
Page: nonced script appends a script from cdn.jsdelivr.net
Result: library did not load (typeof window._ was undefined)
blocked script-src-elem https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js
The same loader pattern with only 'self' and a nonce was blocked, because the CDN was not on the list. The old fix is to add every host to an allowlist, but allowlists are weak: research by Google found most allowlist policies could be bypassed through JSONP endpoints or old libraries hosted on allowed CDNs. That is why modern guidance prefers nonces with 'strict-dynamic'.
Test 5: eval is blocked
Policy: script-src 'nonce-...'
Code: try { eval("1+1") } catch (e) { ... }
Result: eval blocked: EvalError
blocked script-src eval
CSP blocks eval, new Function and string arguments to setTimeout unless you add 'unsafe-eval'. Some older template libraries and source-map tools need eval; prefer replacing them over weakening the policy.
Test 6: images from other origins
Policy: default-src 'self'; script-src 'nonce-...'
Page: <img src="https://www.google.com/favicon.ico"> <img src="/pixel.svg">
Result: external: not loaded, local: loaded
blocked img-src https://www.google.com/favicon.ico
Because the policy had no img-src, it fell back to default-src 'self', and the external image was blocked. Image and connection rules matter more than they seem: attackers who cannot run scripts sometimes leak data through image URLs or fetch calls to their own server, which img-src and connect-src prevent. See our fetch API guide for how connect-src affects requests.
Test 7: inline styles
Policy: style-src 'self'; script-src 'nonce-...'
Page: <p style="color:red"> and <style>body{background:#eef}</style>
Result: text colour rgb(0, 0, 0), background transparent
blocked style-src-attr inline | blocked style-src-elem inline
Both the style attribute and the <style> block were ignored, reported separately as style-src-attr and style-src-elem. Strict style rules break many component libraries and WordPress themes, so most sites allow 'unsafe-inline' for styles while keeping scripts strict. That trade-off is reasonable: injected CSS is far less dangerous than injected JavaScript.
Test 8: Report-Only mode
Header: Content-Security-Policy-Report-Only: script-src 'self' 'nonce-...'
Page: un-nonced inline script
Result: inline script RAN (report only)
blocked script-src-elem inline (reported, not enforced)
With the Report-Only header, the browser evaluated the policy and fired the violation, but still ran the script. That lets you deploy a policy to real users, collect every violation it would cause, fix them, and only then enforce it. Add report-to (with a Reporting-Endpoints header) or the older report-uri directive to send reports to a collection endpoint; we observed violations in the page rather than at an endpoint. Report-Only does not work in a <meta> tag, only as a header.
Key CSP directives
| Directive | Controls |
|---|---|
default-src |
Fallback for types not listed |
script-src |
JavaScript, including inline and eval |
style-src |
CSS files, style blocks and attributes |
img-src, font-src, media-src |
Images, fonts, audio and video |
connect-src |
fetch, XHR, WebSocket and EventSource targets |
frame-src |
What your page may embed in iframes |
frame-ancestors |
Who may embed your page (clickjacking protection) |
object-src |
Plugins; set to 'none' |
base-uri |
Limits the base tag; set to 'none' or 'self' |
form-action |
Where forms may submit |
upgrade-insecure-requests |
Rewrites http resource URLs to https |
CSP is separate from CORS: CORS controls which other sites may read your server’s responses, while CSP controls what your page may load and run.
A strict starter policy
Content-Security-Policy:
script-src 'nonce-{RANDOM}' 'strict-dynamic' https: 'unsafe-inline';
object-src 'none';
base-uri 'none';
frame-ancestors 'self';
This follows the pattern recommended by web.dev and OWASP. The https: and 'unsafe-inline' entries look alarming, but they are fallbacks for very old browsers: browsers that understand nonces ignore 'unsafe-inline' when a nonce is present, and browsers that understand 'strict-dynamic' ignore https:. Generate the nonce on the server for every response and add it to every script tag your templates output.
Tip: if a page is cached by a CDN or a page cache plugin, every visitor gets the same nonce. Either exclude those pages from caching, or use hash-based policies for them.
Rolling out CSP without breaking your site
- Inventory scripts, styles, fonts, frames and API hosts the site uses.
- Deploy the target policy as Report-Only and collect violations for a week or two.
- Fix violations: move inline handlers to files, add nonces, remove eval.
- Switch to the enforcing header, and keep a Report-Only copy of a stricter next version running alongside.
- Check the policy in your release tests, as part of a security regression checklist.
Common mistakes
- Using
'unsafe-inline'for scripts without a nonce, which removes most of the XSS protection. - Reusing a fixed nonce, which an attacker can simply copy from the page source.
- Allowlisting large CDNs or
*, which lets attackers load any script hosted there. - Forgetting
object-src 'none'andbase-uri, two well-known bypass routes. - Leaving Report-Only in place for ever, which reports attacks but never stops them.
- Setting two conflicting CSP headers, for example one from the app and one from the web server: browsers enforce both, so the result is stricter than either.
Final thoughts
A content security policy turns the browser into an enforcement point: code you did not approve does not run. Our tests showed the essentials. Inline scripts without a nonce were blocked, nonced scripts ran, 'strict-dynamic' let trusted loaders work, eval was refused, and Report-Only mode reported problems without breaking anything. Start in Report-Only, move to a nonce-based strict policy, keep styles a little looser if you must, and test the header in every release.
Frequently asked questions
What does a content security policy do?
It tells the browser which sources of scripts, styles, images and other resources a page may use. Anything else is blocked, which stops most injected scripts from running.
What is a CSP nonce?
A random value generated for each response, placed in the policy header and on every trusted script tag. Only scripts with the matching nonce run, and attackers cannot guess it.
What does strict-dynamic mean in CSP?
It lets scripts that were trusted through a nonce or hash load further scripts, which are then trusted too. Supporting browsers ignore host allowlists for scripts when it is present.
How do I test a CSP without breaking my site?
Send it with the Content-Security-Policy-Report-Only header. The browser reports violations but does not block anything, so you can fix problems before enforcing it.
Can I set a CSP in a meta tag?
Yes, for most directives, but the header is preferred. A meta tag cannot use report-only mode or the frame-ancestors directive.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.