Security guide

CSP Nonce for Inline Scripts

The moment you add a Content-Security-Policy header, your inline scripts stop running. The tempting fix is 'unsafe-inline' in script-src — but that undoes the most important XSS protection CSP provides. The correct fix is nonces: a cryptographically random token generated fresh on every request, stamped on each legitimate inline script, verified by the browser.

Why 'unsafe-inline' breaks CSP

CSP’s primary purpose is to block injected scripts. When an attacker finds an XSS vulnerability in your app — a reflected parameter, an unsanitised database value rendered into the page — they can inject a <script> block. Without CSP, that script runs. CSP’s script-src directive is designed to stop it.

But 'unsafe-inline' allows all inline scripts to run, with no discrimination — including one an attacker injected. The directive name says what it is:

Content-Security-Policy: script-src 'self' 'unsafe-inline'

With 'unsafe-inline' present, CSP still blocks scripts loaded from unexpected external domains, so it is not entirely useless — but it no longer defends against the scenario it was primarily designed for: an attacker injecting a <script> block into your page through a vulnerability. The most common attack vector is wide open. HardenCheck flags this as a critical policy weakness.

Never add 'unsafe-inline' to fix a broken inline script. That is trading your most important XSS protection for a few lines of convenience. Use nonces instead.

How nonces work

A nonce is a random 128-bit value your server generates fresh for each HTTP response. It appears in exactly two places:

  1. In the Content-Security-Policy header as 'nonce-BASE64VALUE' inside script-src.
  2. In the nonce attribute on each of your legitimate inline <script> tags.

When the browser parses the page, it checks every inline script: does its nonce attribute match the value in the header? If yes, the script runs. If no — or if the nonce attribute is missing — the script is blocked.

Because the nonce is unguessable and generated fresh on every request, an attacker who injects a <script> block into your page cannot know the current value. Their injected script has no nonce, or a stale one, and the browser blocks it.

Nonces are per-request secrets. They must be generated by a server or edge function — never hardcoded into static HTML. A nonce baked into a static file is visible to anyone who views source, and once known it is useless as a secret.

Nonce syntax: header and HTML

The header includes the nonce token inside script-src:

Content-Security-Policy: script-src 'nonce-rAnd0mBas364=' 'strict-dynamic';

The matching inline script uses the same value as the nonce attribute — note it is not quoted in the attribute:

<script nonce="rAnd0mBas364=">
  // your inline code here
</script>

External scripts loaded with <script src="..."> do not need a nonce when you use 'strict-dynamic' — scripts loaded by a nonce-validated script inherit that trust automatically. See Nonces + strict-dynamic below.

Server-side generation

Generate a fresh nonce for every HTTP response using your platform’s cryptographically secure random number generator. Never reuse a nonce across requests, never hardcode one, and never derive one from predictable data like timestamps or user IDs.

Express / Node.js

const crypto = require('crypto');

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString('base64');
  res.locals.nonce = nonce;
  res.setHeader(
    'Content-Security-Policy',
    `script-src 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'`
  );
  next();
});

In your template, reference the nonce on each inline script tag. EJS: <script nonce="<%= nonce %>">. Handlebars: <script nonce="{{nonce}}">. Pug syntax varies by version.

Next.js App Router (middleware.ts)

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
  const csp = `script-src 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'`;

  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-nonce', nonce);
  requestHeaders.set('Content-Security-Policy', csp);

  const response = NextResponse.next({ request: { headers: requestHeaders } });
  response.headers.set('Content-Security-Policy', csp);
  return response;
}

In your root layout.tsx, read headers().get('x-nonce') and pass it to any <Script> or inline <script> tags that need it.

Django (django-csp)

pip install django-csp
# settings.py
MIDDLEWARE = ['csp.middleware.CSPMiddleware', ...]
CSP_SCRIPT_SRC = ["'self'"]
CSP_INCLUDE_NONCE_IN = ['script-src']

In templates: <script nonce="{{ request.csp_nonce }}">.

Rails (secure_headers gem)

# Gemfile
gem 'secure_headers'

# config/initializers/secure_headers.rb
SecureHeaders::Configuration.default do |c|
  c.csp = {
    script_src: ["'self'", :nonce]
  }
end

In views: <script nonce="<%= content_security_policy_nonce %>">.

Nonces + 'strict-dynamic'

'strict-dynamic' is the production companion to nonces. Without it, every external script your nonce-carrying inline script dynamically loads would need its own nonce — or would be blocked. This breaks tag managers (Google Tag Manager, analytics), lazy-loaded modules, and any third-party script that injects further scripts at runtime.

With 'strict-dynamic', any script loaded by a nonce-validated script inherits that trust automatically. You no longer need to enumerate every CDN domain in script-src. The recommended production pattern is:

Content-Security-Policy: script-src 'nonce-RANDOM' 'strict-dynamic' https: 'unsafe-inline';

The trailing https: and 'unsafe-inline' tokens exist only for backwards compatibility with older browsers that do not understand nonces or 'strict-dynamic'. Any browser that supports nonces ignores both. For the full picture of how 'strict-dynamic' propagates trust through dynamically loaded scripts, see the strict-dynamic guide.

What nonces don’t protect

Nonces close the inline-script XSS door. They are not a complete security solution. Here is what else you need:

ThreatNonce protects?Mitigation
XSS injecting inline <script> Yes —
Compromised CDN serving a modified script No Use SRI hashes (integrity= attribute)
Compromised npm package in your bundle No DepCheck + SRI on CDN assets
eval() executing injected strings No Remove 'unsafe-eval' from script-src
Data URIs used as script sources No Remove data: from script-src
Nonces close the inline-script XSS door. For external scripts, also add integrity attributes (SRI). See the SRI guide.

Verify with HardenCheck

HardenCheck detects 'unsafe-inline' in your script-src as a critical policy weakness. After deploying nonces, verify your policy with HardenCheck — paste your response headers directly into the tool to see your updated CSP grade without modifying your site.

HardenCheck reports a higher score when it sees a nonce or hash pattern ('nonce-' or 'sha256-' / 'sha384-' / 'sha512-') in script-src. The easiest way to get your real headers is curl -I https://your-site.com and paste the output.

Test my headers with HardenCheck →

Related guides

Nonces are one piece of a layered CSP strategy. These guides cover the surrounding territory:

Frequently asked questions

What is a CSP nonce and how does it work?

A nonce (number used once) is a cryptographically random, base64-encoded string generated fresh on every HTTP response. You include the same nonce value in the Content-Security-Policy header (as 'nonce-BASE64VALUE' in script-src) and in the nonce attribute of each legitimate inline script tag. The browser only executes inline scripts whose nonce attribute matches the value in the header. Because the nonce changes on every request, an attacker who injects a <script> tag cannot know the current nonce and cannot make their injected script execute.

Why is 'unsafe-inline' in script-src so dangerous?

Adding 'unsafe-inline' to script-src allows any inline script on the page to execute — including one an attacker injected via XSS. It eliminates the most important protection that Content-Security-Policy provides. With 'unsafe-inline', a CSP still blocks scripts from unexpected external domains, so it is not entirely worthless, but it no longer defends against the scenario CSP was primarily designed for: an attacker injecting a script block into your page through a vulnerability. Nonces preserve that protection while still allowing your own inline scripts to run.

How do I generate a secure nonce server-side?

Use a cryptographically secure random number generator. In Node.js: crypto.randomBytes(16).toString('base64'). In Python: base64.b64encode(os.urandom(16)).decode(). In Ruby: SecureRandom.base64(16). The nonce must be at least 128 bits (16 bytes) of entropy. It must be generated fresh on every HTTP response — never reused across requests, never hardcoded, and never derived from predictable data like timestamps or user IDs.

Can I use a nonce on a fully static site?

Not correctly. A static HTML file has a fixed nonce baked into its content. Once a user reads the page source, they know the nonce. Nonces are only secure when generated fresh per request by a server or edge function that injects the same value into both the HTTP header and the HTML. For fully static sites, use script hashes instead: compute SHA-256 of each inline script’s exact content and include 'sha256-BASE64HASH' in script-src.

Does a nonce replace 'unsafe-inline' completely?

Yes, in modern browsers. When script-src contains a nonce (e.g. 'nonce-abc123'), browsers treat 'unsafe-inline' in the same script-src as if it were absent — the nonce takes precedence. The recommended pattern is: script-src 'nonce-RANDOM' 'strict-dynamic' https: 'unsafe-inline' — where the last two values exist only for older browser compatibility and are ignored by any browser that supports nonces.

What is the difference between a nonce and a hash in CSP?

Both allow specific inline scripts without 'unsafe-inline', but they work differently. A nonce is a per-request secret: a random value you generate for each response. A hash is based on the script’s exact content: you compute SHA-256 of the script text and include the base64-encoded hash in script-src. Hashes are good for static inline scripts that never change; nonces are better for server-rendered content where the inline script body varies per request.

Does HardenCheck check whether my CSP uses nonces?

HardenCheck grades your CSP strength from the response headers. It flags the presence of 'unsafe-inline' in script-src as a critical weakness and reports a higher score when it sees a nonce or hash pattern ('nonce-' or 'sha256-' / 'sha384-' / 'sha512-' in script-src). To test your policy, paste your raw HTTP response headers into HardenCheck’s paste mode.