Adding Nonces to Script Tags
You'll learn how to attach nonce attributes to inline script tags so they're allowed to execute under your Content Security Policy.
Now that you've generated secure nonces, it's time to put them to work. A nonce (number used once) acts like a backstage pass for your inline scripts—only scripts carrying the matching nonce will be allowed to run when you've locked down your CSP.
How It Works
When you set a CSP with script-src 'nonce-abc123', the browser will only execute inline <script> tags that include the attribute nonce="abc123". Any inline script without that exact nonce gets blocked, protecting you from injected malicious code.
Here's the pattern:
<!-- Server generates nonce: "2726c7f26c" -->
<script nonce="2726c7f26c">
console.log('This script is whitelisted!');
</script>
<script>
console.log('This script is BLOCKED - no nonce');
</script>
The HTTP response header would include:
Content-Security-Policy: script-src 'nonce-2726c7f26c'
Key Points
- The nonce value must be randomly generated per page load (as you learned previously)
- The nonce in your CSP header must exactly match the nonce attribute in your script tag
- External scripts loaded via
srcdon't need nonces—only inline scripts - Event handlers like
onclickare also considered inline scripts and would need nonces (or better yet, use proper event listeners instead)
Think of it like a movie premiere: the bouncer (browser) checks everyone's ticket (nonce). Only guests with today's unique ticket code get in—forged or missing tickets are turned away.
Key Takeaway: Adding nonce="your-generated-nonce" to inline script tags whitelists them under CSP, allowing only scripts you've explicitly blessed to execute while blocking injected malicious code.