Nonce-Based Content Security Policy (Nonce-Based CSP)

Security Glossary - Security Headers

Definition: A nonce-based CSP uses a random, single-use token (nonce) generated by the server for each page load. Only script tags that include the matching nonce attribute are allowed to execute. This is the recommended approach for CSP because it blocks injected scripts (which will not have the nonce) while allowing legitimate scripts.

Quick Reference

RequirementDetails
Nonce formatBase64 string, at least 128 bits of entropy
GenerationMust be unique per page load, cryptographically random
Header examplescript-src 'nonce-4AEemGb0xJptoIGFP3Nd'
Script tagscript nonce="4AEemGb0xJptoIGFP3Nd"
CachingNonce 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.

Frequently Asked Questions

How do I implement nonce-based CSP?
Generate a random nonce on the server for each request (at least 128 bits of randomness). Include it in the CSP header as script-src 'nonce-{value}' and add the same nonce as an attribute on each legitimate script tag: <script nonce="{value}">. Most frameworks have middleware for this.
Can I use nonces with inline scripts?
Yes, that is one of the main benefits. Add the nonce attribute to any inline script tag, and it will be allowed to execute. Inline scripts without the nonce are blocked. This lets you use inline scripts securely while still blocking XSS injections.
Disclaimer: DomainOptic provides automated informational scans only. Results do not constitute professional security advice, compliance certification, or a guarantee of security. Always verify findings independently.