Cybersecurity & Privacy

Nonces and Hashes: Allowing Specific Inline Scripts Safely in CSP

Two Ways to Trust a Specific Inline Script

Sometimes you genuinely need an inline script — a small analytics snippet, a bit of page-specific configuration. CSP offers two mechanisms for allowing specific inline content without opening the door to everything: nonces and hashes.

Nonces: A Fresh Secret Per Page Load

A nonce ("number used once") is a random value your server generates fresh for every page load, included both in the CSP header and as an attribute on the specific script tags you want to allow:

Content-Security-Policy: script-src 'nonce-a8f3k2';

Since the value changes every time the page loads, an attacker can't predict it in advance — even if they manage to inject a script tag, they have no way to know what nonce value that particular page load requires, so their injected script gets blocked while your correctly-tagged legitimate script runs.

Hashes: Trusting Exact, Unchanging Content

A hash-based approach computes a cryptographic hash of your inline script's exact content and lists that hash in the policy — only a script whose content matches that exact hash is allowed to run:

Content-Security-Policy: script-src 'sha256-V2kaaafImTjn8RQTWZmF4IfGfQ7Qsqsw9GWaFjzFNPg=';

This works well for genuinely static inline scripts that never change. The tradeoff: even a trivial edit — adding a space, reformatting the code — changes the hash entirely, breaking the policy until you regenerate and update it.

Which to Use When

Why Both Beat unsafe-inline

Both approaches let you allow the specific inline scripts you actually trust, while still blocking anything an attacker manages to inject — the precision 'unsafe-inline' completely lacks, since it allows every inline script indiscriminately, trusted or not.

Ready to build a policy with proper inline script handling?

Open CSP Generator