CSP Nonces Explained: Safer Inline Scripts
Content-Security-Policy nonces let you allow specific inline scripts without opening unsafe-inline. Learn how nonces work, how they differ from hashes, and rollout tips.
A CSP nonce is a random, unguessable value your server generates per response and places on both the Content-Security-Policy header and the inline <script> tags you intentionally trust. Browsers run only those inline scripts that carry the matching nonce, which removes the need for a blanket 'unsafe-inline'.
Nonces are one of the cleanest ways to tighten CSP on apps that still need a small amount of inline bootstrapping. For broader CSP setup, see the Content-Security-Policy setup guide.
How a nonce flows through a request
- 1Server generates a cryptographically strong random string for this response only.
- 2Server sends
Content-Security-Policyincludingscript-src 'nonce-…'. - 3Server renders trusted inline scripts as
<script nonce="…">. - 4Browser executes matching nonced scripts and blocks others.
Content-Security-Policy: default-src 'self'; script-src 'nonce-rAnd0m123' 'strict-dynamic' <script nonce="rAnd0m123">window.__BOOT=true</script>
Nonces vs hashes
- Nonces change every response; ideal when inline content varies or is templated.
- Hashes (
'sha256-…') allow a fixed inline block by content fingerprint; ideal for rare static snippets. - `'strict-dynamic'` lets nonced or hashed scripts load additional scripts, which simplifies modern bundles when used carefully.
A nonce must be unique per response (or at least unpredictable). Reusing one static nonce in a config file is equivalent to allowing anyone who learns it to inline scripts.
Framework notes
Many modern frameworks can emit nonces into both the CSP middleware and the HTML template. Wire the same request-scoped value through; do not hardcode an example string from documentation into production.
Roll out without breaking the UI
- 1Start with
Content-Security-Policy-Report-Onlyand collect violations. - 2Add nonces to first-party inline scripts you still need.
- 3Remove
'unsafe-inline'once reports are clean. - 4Enforce the policy and monitor with CSP error fixes as a troubleshooting map.
Verify on the live site
View source on a authenticated page and confirm the nonce in the header matches the script attributes. Then run a PatchPings scan to grade CSP presence. Scanners will not invent a nonce for you, but they will show whether CSP is missing, report-only, or overly permissive.
Nonces turn CSP from a blunt 'unsafe-inline' switch into a precise allow-list. Generate them per response, keep them out of static config, and pair them with the rest of your XSS defences from clickjacking, XSS and CSRF explained.
