Catalog My learning Blog
Browser Security Headers: CORS, CSP and Cookies Explained · Phase 3 · Lesson 14 · 7 min read

CSP Nonce vs Hash vs unsafe-inline

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Correct Per-Response Nonce, and the Ways It Goes Wrong
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Compare the three mechanisms for permitting inline script, explain why a nonce must be unpredictable and regenerated on every response, and choose correctly between nonces and hashes for a given deployment.

Concept Explanation

By default, a CSP that specifies script-src blocks all inline script: script elements with inline content, javascript: URLs, and inline event handler attributes such as onclick and onerror. That blanket block is where most of CSP's value comes from, because injected XSS payloads are overwhelmingly inline. It is also what makes CSP hard to adopt, since real applications have inline scripts, and the three ways to permit them differ enormously in security.

The keyword unsafe-inline permits all inline script unconditionally. It is honestly named. A policy containing script-src 'self' 'unsafe-inline' provides essentially no XSS protection at all, because the injected payload is inline and is therefore permitted along with the legitimate inline code; the browser has no way to tell them apart. It remains extremely common in deployed policies, and it is the single largest reason the Google survey found most real policies bypassable. Treat its presence in a policy as equivalent to having no script protection.

A nonce is a random token generated per response, placed in the policy as 'nonce-VALUE' and repeated as a nonce attribute on each script tag the server itself emitted. The browser executes a script only if its nonce attribute matches the policy value. This works because the attacker, injecting into the page content, does not know the token: it was generated after their payload was stored and it is different on every response. Three properties are mandatory. The nonce must be cryptographically random, at least 128 bits, generated with a secure random source rather than a timestamp or a counter. It must be unique per response, never per session, per deploy, or cached. And the page must not be cached in a way that serves the same nonce to different requests, which is why a static cached page and nonces are incompatible.

A hash source, written as 'sha256-BASE64', permits a specific inline script whose content hashes to that exact value. No attribute is needed on the script tag; the browser hashes the element's text content and compares. Hashes suit static content perfectly, since the hash can be computed at build time and the page can be cached indefinitely, which is precisely where nonces fail. Their weakness is brittleness: any change to the script content, including a single whitespace character, invalidates the hash, and hashes do not work for inline event handler attributes at all, nor for dynamically generated inline script.

There is one more trap specific to nonces and external scripts. A nonce on a script tag also authorizes that tag to load an external source, bypassing the host allowlist. If an attacker can inject an attribute into an existing nonced script tag, or if a templating system copies the nonce onto attacker-influenced markup, they gain arbitrary script loading. Related, and more common: never place a nonce into markup that reflects user input, and never expose the nonce value anywhere it can be read cross-origin, such as in a URL. The strict-dynamic keyword, covered in the bypass lesson, builds on nonces deliberately to let a nonced script load its own dependencies without an allowlist.

MechanismSecurityCachingBest for
'unsafe-inline'None; injected inline script is permitted tooAnyNothing; treat as absence of protection
NonceStrong, if random and per-responseIncompatible with caching the HTMLDynamically rendered pages
HashStrong, and pinned to exact contentFully cacheableStatic pages and build-time known inline scripts
Nonce plus 'strict-dynamic'Strongest practical optionSame constraint as noncesApplications with dynamic script loaders

Worked Example: A Correct Per-Response Nonce, and the Ways It Goes Wrong

The middleware below shows the correct shape. The commented failures underneath are the three mistakes that appear most often in real deployments, each of which reduces a nonce policy to roughly the security of unsafe-inline.

JavaScript
// CORRECT: 128 bits of CSPRNG output, fresh on every single response
app.use((req, res, next) => {
  res.locals.nonce = crypto.randomBytes(16).toString('base64');
  res.setHeader('Content-Security-Policy', [
    "default-src 'self'",
    `script-src 'nonce-${res.locals.nonce}' 'strict-dynamic' https: 'unsafe-inline'`,
    "object-src 'none'",
    "base-uri 'none'",
  ].join('; '));
  // Note: 'unsafe-inline' and https: above are IGNORED by browsers that
  // understand nonces and strict-dynamic; they are backward-compatibility
  // fallbacks for older browsers only.
  next();
});

// In the template:
// <script nonce="<%= nonce %>">initApp();</script>

// FAILURE 1 - one nonce for the whole process: an attacker reads it once
// from any page and reuses it forever.
// const NONCE = crypto.randomBytes(16).toString('base64');   // module scope

// FAILURE 2 - predictable source: guessable, therefore forgeable.
// const nonce = Buffer.from(String(Date.now())).toString('base64');

// FAILURE 3 - the HTML is cached by a CDN, so thousands of users receive
// a page whose nonce an attacker has already seen. Nonced HTML must be
// no-store, or the nonce must be injected at the edge per response.

// Hash alternative for a static inline script:
//   echo -n "initApp();" | openssl dgst -sha256 -binary | openssl base64
//   script-src 'sha256-Nv8yC...='
Three inline-script permission mechanisms evaluated against the same injected payload, showing unsafe-inline admitting it, a per-response nonce rejecting it for lack of a matching token, and a hash rejecting it for content mismatch.
Three inline-script permission mechanisms evaluated against the same injected payload, showing unsafe-inline admitting it, a per-response nonce rejecting it for lack of a matching token, and a hash rejecting it for content mismatch.

Real-World Examples

  • Google's 2016 CCS study found that the overwhelming majority of deployed CSP policies were bypassable, with the presence of unsafe-inline in script-src among the dominant causes, since a policy permitting all inline script cannot distinguish an injected payload from the page's own code; the same research introduced the nonce plus strict-dynamic pattern as the practical alternative and is the origin of the approach now recommended by browser vendors.
  • Research published in 2018 demonstrated CSS-based nonce exfiltration, in which attribute selectors in injected CSS leak a script tag's nonce value character by character through selective resource loading; the finding prompted the CSP specification to hide the nonce content attribute from the DOM after parsing, which is why reading a script element's nonce attribute through getAttribute now returns an empty string in modern browsers.
WarningGenerate every nonce from a cryptographically secure random source, at least 128 bits, once per HTTP response, and never cache HTML that carries one. A nonce reused across responses, derived from a timestamp, or served from a CDN cache is a nonce an attacker can obtain and replay, which reduces the entire policy to the security of unsafe-inline.

Review Questions & Answers

Because XSS payloads are overwhelmingly inline, and unsafe-inline tells the browser to execute all inline script without distinction. The browser cannot tell which inline script the developer wrote and which an attacker injected, since both are simply inline content in the delivered document. A policy containing it still restricts external script sources and other resource types, but the primary attack it was meant to blunt passes through unimpeded.

The nonce works only because the attacker cannot know it at the time their payload is stored or reflected. A nonce that persists across responses can be read by the attacker from any page they can view, or obtained once and embedded in a stored payload that will then be executed on every subsequent page view. Per-response generation means the value the attacker saw is already invalid by the time their payload is rendered to a victim.

A hash is better when the inline script content is known at build time and the HTML is served from a cache or CDN, because hashes require no per-response server work and place no constraint on caching, whereas nonced HTML cannot be cached at all. The cost is brittleness: any change to the script content, including whitespace, invalidates the hash, and hashes cannot authorize inline event handler attributes or dynamically generated inline script.

It is not contradictory, it is a deliberate backward-compatibility pattern. The specification says that a browser which understands nonces must ignore unsafe-inline entirely when a nonce is present, so modern browsers enforce the nonce. Older browsers that do not understand nonces would otherwise block all inline script and break the page, so unsafe-inline gives them a functional fallback. The same reasoning applies to listing https: alongside strict-dynamic.