Nonce-Based Content Security Policy (Nonce-Based CSP)
Quick Reference
| Requirement | Details |
|---|---|
| Nonce format | Base64 string, at least 128 bits of entropy |
| Generation | Must be unique per page load, cryptographically random |
| Header example | script-src 'nonce-4AEemGb0xJptoIGFP3Nd' |
| Script tag | script nonce="4AEemGb0xJptoIGFP3Nd" |
| Caching | Nonce must change on each response (incompatible with full-page caching) |
Why Nonce-Based CSP Matters
Nonce-based CSP is considered the gold standard for XSS prevention via CSP. Unlike allowlist-based CSPs that trust entire domains (which can be bypassed if any script on those domains is vulnerable), nonce-based CSPs only trust specific script tags that carry the server-generated nonce.
The nonce must be cryptographically random and different for every page response. If the nonce is predictable or reused, an attacker could include it in their injected script. Most web frameworks have built-in support for generating and inserting CSP nonces automatically.
Combined with strict-dynamic, nonce-based CSP provides strong protection even for complex applications. The nonce trusts the initial scripts, and strict-dynamic allows those trusted scripts to load additional resources. This approach is recommended by Google's CSP documentation and the OWASP CSP cheat sheet.
How to Verify
A security audit checks whether your CSP uses nonces or hashes rather than domain allowlists. Verify that nonces are cryptographically random and change with every response. Check that inline scripts without nonces are properly blocked.