Skip to content
jshacks.dev
Security

Set a Content Security Policy with nonces

Generate a fresh random nonce per response and put it in the Content-Security-Policy header and on each script tag, so only your scripts run.

1 min read
Summarize in AI

A CSP that allows 'unsafe-inline' does nothing against injected scripts. A nonce lets you keep inline scripts and still block the ones an attacker adds, as long as the value changes on every response.

nonce.jsJavaScript
import { randomBytes } from 'node:crypto';

function cspFor() {
  const nonce = randomBytes(16).toString('base64');
  const header = `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`;
  return { nonce, header };
}

const { nonce, header } = cspFor();
console.log(header.length > 60);
console.log(`<script nonce="${nonce}">init()</script>`.startsWith('<script nonce="'));
Text
true
true

Send header as the Content-Security-Policy response header and print the same nonce in each trusted <script nonce="..."> tag. The browser runs a script only when its nonce matches the header, and an injected <script> has no way to know a value that did not exist until this response. randomBytes comes from the operating system's CSPRNG, which is what the MDN CSP guide asks for.

A cached page keeps its old nonce, so a nonce cannot be used on pages served from a CDN cache or static files. Use hashes there instead.

Share

More snippets

Security

Report CSP violations to an endpoint

Receive Content Security Policy violation reports at an endpoint with the report-to and report-uri directives, and parse what the browser sends.

1 min read
Security

Sandbox untrusted code in a worker

Run untrusted code in a worker thread with limited memory and a kill timeout, and know what a worker does not isolate.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.