opyeb srihash

CSP hashes and nonces — two ways to allow inline code

2026-11-29 · 2 min read

There are two ways to allow inline code: a hash when the content is fixed, a nonce when it changes per request.

A hash is an identity made of content

With 'sha384-…' in script-src, the browser computes a digest of each inline block on the page and compares it with the list. Only matching blocks run.

The advantage is that the value does not change per request, which suits inline scripts baked into static HTML or finalised at build time. The cost is that a one-character edit changes the hash, so the build has to recompute it.

Content-Security-Policy: script-src 'self' 'sha384-SMPwvYr9eRwR/axEGrORdN1VwWIaVuY2TTdeGWGkL6oeEalrd4V2wQI141RcZnN4'

A nonce is a per-request ticket

A nonce is a value the server generates for each response and writes into both the script tag and the header. The browser runs only blocks whose value matches.

That fits server-rendered pages where the code differs per response. Use at least 16 random bytes (128 bits), because a guessable nonce is no protection at all.

Choosing between them

Most cases fall out of this table.

SituationPreferWhy
Fixed inline script in static HTMLHashContent never changes, so neither does the value
SSR or templates generating code per requestNonceThe value must differ per response
Build tool injects inline codeHashComputable from the build output
Many pages share one headerNonceOne header covers different code per page

unsafe-inline and strict-dynamic

When a hash or nonce is present in a directive, modern browsers ignore 'unsafe-inline' in that same directive. Unless you are targeting an old browser, there is no reason to keep it.

'strict-dynamic' makes host sources (such as https://cdn.example.com) irrelevant and trusts scripts loaded by a nonce- or hash-approved script. It helps pages with dynamic loaders, but only enable it when you understand the behaviour.

Syntax mistakes that cost hours

Hashes and nonces must be wrapped in single quotes. Without quotes the browser reads the token as a host source and ignores it.

Directives are separated by semicolons, a repeated directive is ignored the second time, and 'none' is only valid on its own.

Questions

With a hash in place, can I drop unsafe-inline?

Yes. Modern browsers ignore unsafe-inline whenever a hash or nonce exists, so removing it makes the policy state exactly what you mean.

Does a per-request nonce break caching?

The HTML carrying the CSP header should not be cached, or only briefly. Static assets can still be cached normally.

Sources

Every example here can be pasted into the workbench as it is.

Open the workbench