Generating Secure Nonces
What you'll learn: How to create cryptographically random nonces server-side for each HTTP request to secure your Content Security Policy.
Now that you understand what CSP nonces are, you need to know how to generate them properly. A nonce is only secure if it's truly unpredictable—meaning attackers can't guess what the next nonce will be.
Why Cryptographic Randomness Matters
Think of a nonce like a unique, one-time password for each page load. If you use predictable patterns (like incrementing numbers or simple timestamps), an attacker who sees one nonce could guess future ones. That defeats the entire purpose of using nonces for CSP protection.
Server-Side Generation is Required
Nonces must be generated on the server for each request because:
- The server creates the nonce before sending the HTML
- It embeds that nonce in both the CSP header and your
<script>tags - A new, unpredictable nonce is created for every page load
You cannot generate secure nonces in client-side JavaScript—by the time JavaScript runs, the CSP header has already been sent and processed by the browser.
What Makes a Nonce Secure
A proper nonce should be:
- At least 128 bits (16 bytes) of cryptographically random data
- Base64-encoded for safe transmission in HTTP headers
- Unique per request (never reused across page loads)
- Generated using your platform's cryptographic random number generator (not
Math.random())
Most server frameworks provide built-in functions for this—like Node.js's crypto.randomBytes(), Python's secrets module, or PHP's random_bytes().
Key Takeaway: Generate CSP nonces server-side using cryptographically secure random functions, creating a unique, unpredictable value of at least 128 bits for every single HTTP request.