SiteTidy
HomeGuidesConfiguring Content Security Policy (Part 3): Nonces, Hashes and strict-dynamic
Security

Configuring Content Security Policy (Part 3): Nonces, Hashes and strict-dynamic

Implement a modern strict CSP with per-response nonces, script hashes and strict-dynamic. Learn the trade-offs for server-rendered apps, static sites, SPAs and third-party loaders.

Published on August 15, 2026Updated August 31, 2026
Configuring Content Security Policy (Part 3): Nonces, Hashes and strict-dynamic

If Part 1 was the reason to use a strict Content Security Policy, this is the part where we make it real.

The core idea is simple:

stop trusting scripts because they came from an allowed hostname; start trusting scripts because you explicitly marked that exact execution path as authorised.

Modern CSP does that primarily with nonces and hashes.

For many applications, those two mechanisms are the difference between a CSP that looks impressive and a CSP that meaningfully reduces XSS exploitability.

This guide covers how they work in production, where they fit, how strict-dynamic changes script loading, and the implementation mistakes that can quietly destroy the protection.

The script-trust problem

A traditional allowlist might look like:

Content-Security-Policy:
  script-src 'self' https://cdn.example.com https://analytics.example.com

That says:

Any script from my origin?                 trusted
Any script from cdn.example.com?           trusted
Any script from analytics.example.com?     trusted
Anything else?                             blocked

The problem is the size of each trust bucket.

If one allowed origin exposes a dangerous JSONP endpoint, user-controlled file path, compromised asset or vulnerable script gadget, your CSP may still allow an attacker to execute code from that trusted location.

A strict policy changes the question:

Did I explicitly authorise THIS script execution?

That is a much narrower trust decision.

Nonce-based CSP in one diagram

A server generates a fresh random value for the response:

fN03mE9Dq7LwP2aKx8V1ug==

It puts the value into both the CSP header and trusted script tags:

Content-Security-Policy:
  script-src 'nonce-fN03mE9Dq7LwP2aKx8V1ug=='
<script nonce="fN03mE9Dq7LwP2aKx8V1ug==" src="/app.js"></script>

The browser sees:

CSP nonce  == script nonce ?
          yes -> allow
           no -> block

An injected script does not know the nonce in advance:

<script src="https://evil.example/x.js"></script>

so it is blocked.

Generate a new nonce for every HTML response

The security property comes from unpredictability.

A nonce must be:

  • generated with a cryptographically secure random source;
  • unpredictable;
  • different for every response;
  • encoded safely for use in the policy and HTML.

web.dev recommends a strong random value, commonly at least 128 bits before encoding.

In Node/Express, a simple pattern is:

import crypto from 'node:crypto';

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString('base64');

  res.locals.cspNonce = nonce;

  res.setHeader(
    'Content-Security-Policy',
    `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`
  );

  next();
});

Then the server-side template deliberately applies it:

<script nonce="{{ cspNonce }}" src="/assets/app.js"></script>

The exact syntax depends on your framework. The trust model does not.

Do not derive the nonce from predictable request data

Bad ideas include:

hash(timestamp)
userId + date
request counter
session ID
fixed config value

Even if the resulting string looks random, predictable inputs can make it guessable.

Use a CSPRNG.

There is no benefit in inventing your own nonce-generation scheme.

Reusing one nonce within a page is normal

You do not need a different nonce for every trusted script on the same response.

This is perfectly valid:

<script nonce="ABC" src="/runtime.js"></script>
<script nonce="ABC" src="/app.js"></script>
<script nonce="ABC">
  window.boot = { locale: 'en-GB' };
</script>

provided the response header contains:

script-src 'nonce-ABC'

The nonce’s “used once” property means fresh per response, not necessarily unique per element.

The dangerous nonce middleware pattern

Avoid this design:

Render arbitrary HTML
      │
      ▼
Search final HTML for every <script>
      │
      ▼
Inject the CSP nonce automatically

Why?

Because if attacker-controlled content has already introduced a script element before that post-processing step, your middleware may bless the attacker’s script with the nonce too.

OWASP explicitly warns against generic middleware that adds nonces to every script tag.

The trusted rendering layer should know which script elements are application-owned and add the nonce when those elements are produced.

Nonces and full-page caching

Per-response nonces create an architectural consequence.

If your HTML is cached as one static object at the CDN for an hour, you cannot safely bake one nonce into that object and reuse it for every visitor.

A nonce should change for every response.

Options include:

  • generate HTML dynamically;
  • inject the nonce at an edge/server layer per response;
  • use a hash-based CSP instead;
  • restructure the page so static HTML does not rely on inline scripts.

This is why hash-based policies often fit static-site architectures better.

Hash-based CSP

Instead of generating a random token, a hash policy trusts the exact script content.

Suppose your page contains:

<script>
  window.appConfig = { environment: 'production' };
</script>

You hash the text inside the script with SHA-256, SHA-384 or SHA-512, Base64 encode the result, and put it into the CSP:

Content-Security-Policy:
  script-src 'sha256-BASE64_HASH'

The browser hashes the script it sees.

If the value matches, it executes.

If an attacker changes the script or inserts a different one, the hash will not match.

Whitespace counts

Hashes are exact.

These may produce different hashes:

console.log('hello');

and:

console.log( 'hello' );

So can a trailing newline.

That is why hash-based CSP is easiest when the relevant script content is stable and generated deterministically.

If your build reformats or fingerprints inline code on every release, regenerate the CSP hashes as part of the build.

External scripts and the integrity attribute

For an external script authorised by a CSP hash, MDN notes that the element also needs the corresponding integrity metadata.

Conceptually:

<script
  src="/assets/app.js"
  integrity="sha384-BASE64_HASH">
</script>

with a matching CSP source:

script-src 'sha384-BASE64_HASH'

This intersects with Subresource Integrity (SRI), which is a separate browser feature that verifies that fetched resource bytes match an expected hash.

CSP and SRI solve related but different problems:

CSP hash -> is this script authorised to execute?
SRI      -> did the fetched resource match expected bytes?

Using both can provide stronger guarantees for stable external assets.

When to choose a nonce

Nonce-based strict CSP is usually a good fit when:

  • HTML is rendered dynamically;
  • you control the server response;
  • you can inject a fresh value into the header and trusted elements;
  • inline bootstrap/configuration scripts change per request;
  • your server-side framework can propagate nonce values cleanly.

Typical examples:

  • ASP.NET MVC/Razor;
  • Next.js SSR;
  • Nuxt SSR;
  • Django templates;
  • Rails;
  • Express/EJS/Handlebars;
  • server-rendered PHP.

When to choose hashes

Hash-based policies often fit better when:

  • HTML is static;
  • pages are served directly from a CDN/object store;
  • assets are produced at build time;
  • inline scripts rarely change;
  • you cannot generate per-request HTML.

Typical examples:

  • Astro static output;
  • static React/Vue builds;
  • documentation sites;
  • Jamstack sites;
  • CDN-cached generated HTML.

That said, a static SPA can also avoid inline scripts entirely and use a carefully designed policy around its external bundles.

The architecture should drive the strategy.

You can use more than one nonce/hash source

A script directive can authorise multiple hashes:

script-src
  'sha256-HASH_ONE'
  'sha256-HASH_TWO'

Likewise, a nonce source can coexist with hashes where there is a genuine reason.

Do not make the policy more complex than necessary, but mixed strategies can be useful during migration.

What strict-dynamic actually means

Consider this trusted loader:

<script nonce="ABC" src="/loader.js"></script>

Inside /loader.js:

const s = document.createElement('script');
s.src = 'https://widgets.example.com/widget.js';
document.head.appendChild(s);

Without strict-dynamic, the dynamically inserted child script may be blocked unless separately authorised.

With:

script-src 'nonce-ABC' 'strict-dynamic'

the trust given to the nonce-bearing loader can propagate to scripts it loads programmatically.

This is extremely helpful for:

  • module/loaders that create script elements;
  • tag managers;
  • complex third-party bootstrap scripts;
  • code splitting systems;
  • applications where the initial trusted bundle loads further chunks dynamically.

strict-dynamic changes how host allowlists behave

This is a subtle but important CSP Level 3 rule.

If strict-dynamic is active alongside a valid nonce/hash, modern supporting browsers ignore host and scheme source expressions for script loading, including values such as:

'self'
https:
https://cdn.example.com

and also ignore 'unsafe-inline' in that context.

So this:

script-src 'nonce-ABC' 'strict-dynamic' 'self' https://cdn.example.com

should not be read as:

allow nonce scripts + self + CDN

in modern CSP3 browsers.

The nonce/hash trust model dominates.

That catches people out when they add strict-dynamic to an existing allowlist policy without understanding the semantic change.

Why backwards-compatible strict CSP examples look strange

You may encounter a policy like:

script-src 'unsafe-inline' https: 'nonce-ABC' 'strict-dynamic'

At first glance, that seems to defeat the whole purpose.

The idea is browser fallback across CSP generations:

Old CSP1 browser   -> 'unsafe-inline' https:
CSP2 browser       -> nonce + https:
CSP3 browser       -> nonce + strict-dynamic

Modern browsers that understand nonces/strict-dynamic ignore the weaker fallback expressions in the relevant way.

web.dev notes that modern browser support for strict CSP is now broad enough that many sites do not need complicated legacy fallbacks unless they explicitly support old clients.

Avoid compatibility cargo culting. Know which browsers you support.

strict-dynamic is not “trust all dynamically loaded scripts”

It is easy to describe it too loosely.

It does not mean:

any script created with JavaScript is automatically safe

It means trust can propagate from a nonce/hash-authorised root script through specific dynamically created script-loading paths.

That creates a new responsibility:

your trusted scripts must not use attacker-controlled values to create executable script sources.

Bad pattern:

const url = new URLSearchParams(location.search).get('script');
const s = document.createElement('script');
s.src = url;
document.body.appendChild(s);

If this code executes inside a trusted strict-dynamic root, CSP may not rescue you from the unsafe loader logic.

Trusted code must still be secure code.

Nonce-hiding in the DOM

Browsers generally hide nonce values from ordinary attribute access in ways intended to reduce nonce exfiltration through CSS selectors and similar techniques, while exposing them through the element’s .nonce property for legitimate script use.

Do not rely on “the nonce is secret because users cannot view source”.

The nonce does not need to be secret after the page is delivered. The important property is that an attacker cannot predict it before injection and cause arbitrary injected markup to receive it.

Do not put the nonce in URLs

Avoid patterns such as:

<script src="/app.js?nonce=ABC"></script>

or exposing it in analytics/query strings.

The nonce belongs in the CSP source expression and the nonce attribute.

Leaking it into URLs can create unnecessary logging, referrer and cache exposure.

Nonces for styles

Nonce sources are also applicable to <style> elements.

For example:

style-src 'nonce-ABC'
<style nonce="ABC">
  .critical { display: block; }
</style>

This can help applications that need server-rendered inline style blocks.

It does not mean every style="..." attribute automatically becomes allowed. Inline style attributes are a separate CSP behaviour.

Hashes for styles

Static inline style blocks can likewise be authorised using hashes:

style-src 'sha256-HASH'

That can be useful for static critical CSS where the bytes are deterministic.

As with script hashes, formatting changes require a new hash.

Inline event handlers are a migration problem

A strict nonce policy does not simply make this safe:

<button onclick="save()">Save</button>

The nonce applies to script/style elements, not arbitrary event-handler attributes.

Refactor inline handlers into trusted JavaScript:

<button id="save">Save</button>
document.getElementById('save').addEventListener('click', save);

There are CSP mechanisms such as hashes and 'unsafe-hashes' that can authorise specific inline handlers in migration scenarios, but they should not be your first design choice for new code.

Part of adopting strict CSP is removing HTML-as-JavaScript patterns.

eval() is a separate problem

A valid nonce does not grant permission to eval() automatically.

Strict script policies normally block string-to-code APIs such as:

eval(code)
new Function(code)

unless 'unsafe-eval' is added.

If production breaks because a library requires unsafe-eval, investigate:

  • is it a development-only build?
  • is there a CSP-compatible build?
  • can the dependency be upgraded?
  • is the functionality genuinely needed?

Do not weaken the entire script execution model because one old library chose a dangerous implementation technique.

Check what production actually serves

A strict CSP can be correct in application code and still disappear at a proxy/CDN layer. Inspect the final public response and the rest of your security headers after every significant configuration change.

Run Free Audit →

Example: ASP.NET-style per-response nonce

A simplified server-side flow in .NET might look conceptually like this:

using System.Security.Cryptography;

app.Use(async (context, next) =>
{
    var bytes = RandomNumberGenerator.GetBytes(16);
    var nonce = Convert.ToBase64String(bytes);

    context.Items["CspNonce"] = nonce;

    context.Response.OnStarting(() =>
    {
        context.Response.Headers.ContentSecurityPolicy =
            $"script-src 'nonce-{nonce}' 'strict-dynamic'; " +
            "object-src 'none'; base-uri 'none'";

        return Task.CompletedTask;
    });

    await next();
});

Then the rendering layer needs deliberate access to the nonce:

<script nonce="@Model.CspNonce" src="/js/app.js"></script>

Production implementation details depend on your framework and rendering architecture, but three guarantees must hold:

fresh random nonce per response
same nonce in CSP + trusted elements
no automatic blessing of attacker-injected elements

Example: static Astro-style hash policy

For a statically generated site, a build pipeline can:

  1. identify inline scripts;
  2. hash their final output bytes;
  3. generate CSP hash expressions;
  4. emit the header through the hosting platform/CDN configuration.

Conceptually:

Astro build
   │
   ├── generate HTML
   ├── collect inline script content
   ├── SHA-256 each script
   └── generate CSP header

Because the content is immutable until the next deployment, the hashes remain valid.

If a minifier or plugin changes script content after the hashes are calculated, the policy breaks — so calculate hashes from the final delivered representation.

Nonce vs hash: practical comparison

                            Nonce                 Hash
-----------------------------------------------------------------
Changes per response        yes                   no
Works with static HTML      awkward               excellent
Dynamic inline config       excellent             awkward
Requires server injection   yes                   no at runtime
Breaks on script edit       no                    yes (rehash)
Good for SSR                excellent             possible
Good for CDN-static pages   difficult             excellent

Do not choose based on which example is shorter.

Choose based on how your HTML is produced.

What about external third-party scripts?

Suppose you have:

<script nonce="ABC" src="https://tag.example.com/loader.js"></script>

The nonce explicitly trusts that loader.

With strict-dynamic, the loader can potentially bring in child scripts without you maintaining a giant list of every downstream hostname.

This solves CSP maintenance pain.

It does not solve vendor compromise.

You are intentionally trusting loader.js to execute in your page. If the vendor serves malicious code from that same trusted entry point, CSP is not a sandbox around it.

Keep third-party JavaScript to the minimum your product genuinely needs.

Combine strict CSP with other controls

A strong browser-security posture may include:

  • strict CSP;
  • safe DOM APIs / output encoding;
  • Trusted Types where appropriate;
  • Subresource Integrity for stable third-party assets;
  • secure cookies;
  • frame-ancestors;
  • Referrer-Policy;
  • Permissions-Policy;
  • HTTPS/HSTS;
  • dependency and supply-chain controls.

No single header replaces secure application design.

Debugging strict CSP failures

When a script does not run, classify the failure.

No valid nonce

Console often indicates the inline/external script was refused because it did not satisfy script-src.

Check:

  • is the nonce attribute present?
  • does it exactly match the header value?
  • was a fresh nonce generated for this response?
  • did a proxy cache HTML from another response?

Hash mismatch

Check:

  • are you hashing exactly the content inside the element?
  • did whitespace/minification change?
  • was the hash calculated before a build transform?
  • for external scripts, is integrity present and correct?

Dynamic child script blocked

Check:

  • is strict-dynamic intended?
  • was the root script nonce/hash authorised?
  • is the child inserted programmatically or parser-inserted in a way that affects CSP behaviour?

eval() blocked

Find the dependency/code path using string-to-code execution rather than immediately adding 'unsafe-eval'.

A migration sequence that works

If your application currently uses:

script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn1.example https://cdn2.example

moving straight to strict CSP in one deployment may be unrealistic.

Use a staged migration:

1. Inventory inline scripts / handlers / eval usage
2. Move event handlers into external/trusted JS
3. Remove unnecessary eval dependencies
4. Choose nonce or hash strategy
5. Add nonce/hash to trusted roots
6. Test strict-dynamic where needed
7. Deploy equivalent policy in Report-Only
8. Analyse real violations
9. Enforce for a controlled audience/environment
10. Remove obsolete host allowlists and unsafe keywords

The migration work is often mostly JavaScript hygiene, not header syntax.

The strict-CSP sanity check

If an attacker can inject a new `