Nonce Lifecycle and Reuse
You'll learn why nonces must be unique per request and the severe security risks introduced by reusing them.
What Is the Nonce Lifecycle?
A nonce (number used once) in Content Security Policy has a simple but critical lifecycle: generate it fresh on the server for each HTTP response, embed it in both your CSP header and inline scripts/styles, then never use it again.
The entire security model of nonces depends on their uniqueness. When a browser sees a nonce in your CSP header, it trusts that any script with that matching nonce value came from your server for this specific request. If you reuse the same nonce across multiple page loads, you've essentially created a permanent "password" that attackers can exploit.
The Security Risk of Nonce Reuse
Imagine reusing the same nonce value like "abc123" for all requests. An attacker who discovers this nonce (perhaps through viewing your page source once) can now inject malicious scripts with that same nonce value. If they trick a user into loading content with <script nonce="abc123">stealCookies()</script>, the browser will execute it—because it trusts that nonce!
Think of it like hotel key cards: each guest gets a new, unique key that expires after checkout. If the hotel reused the same key for every guest forever, anyone who once stayed there could return anytime.
Proper Lifecycle Management
- Generate a cryptographically random nonce on the server
- Include it in the CSP header for that response
- Use it for inline scripts/styles in that HTML document only
- Discard it—never store or reuse it for future requests
Key Takeaway: Nonces must be unique per page load; reusing nonces destroys CSP's protection by giving attackers a predictable bypass token.