The HTML nonce attribute
The HTML nonce attribute holds a one-time cryptographic token that a Content-Security-Policy can use to allow a specific inline <script> or <style> while blocking all others. It is a global attribute; the server must generate a fresh, random, unguessable nonce on every response.
Overview
A "nonce" is a number used once. With a strict Content-Security-Policy you can forbid all inline scripts and styles, then selectively allow trusted ones by giving them a nonce that matches the value in your Content-Security-Policy response header.
For this to be safe the nonce must be cryptographically random and generated anew on every page load. A fixed nonce is no better than no CSP. Browsers also hide the attribute value from the DOM (it is only readable through the element.nonce property) to block CSS attribute-selector and dangling-markup leaks.
Syntax
<!-- HTTP response header (fresh 128-bit base64 token per request) -->
Content-Security-Policy: script-src 'nonce-8IBTHwOdqNKAWeKl7plt8g=='; style-src 'nonce-8IBTHwOdqNKAWeKl7plt8g==';
<!-- Matching HTML elements -->
<script nonce="8IBTHwOdqNKAWeKl7plt8g==">console.log('Allowed');</script>
<style nonce="8IBTHwOdqNKAWeKl7plt8g==">.banner { color: #1565c0; }</style>
Values
| Value |
|---|
| A random, single-use, base64 token generated per request. |
Try it: CSP nonce simulator
Generate a fresh 128-bit base64 nonce in your browser, toggle Content Security Policy Level 3 directives, and see which script tags execute or get blocked.
Example
<!-- Server sends: Content-Security-Policy: script-src 'nonce-r4nd0m' -->
<script nonce="r4nd0m">/* this inline script is allowed */</script>
Server-side recipes
Drop-in examples for generating a per-request token in PHP, Node, Nginx, and Cloudflare Workers.
Generate the nonce before any response body is sent, attach the CSP header, and escape the token when rendering HTML.
<?php
$nonce = base64_encode(random_bytes(16));
header("Content-Security-Policy: script-src 'nonce-{$nonce}' 'strict-dynamic' https:; object-src 'none'; base-uri 'none';");
?>
<script nonce="<?= htmlspecialchars($nonce, ENT_QUOTES, 'UTF-8') ?>">
console.log('Trusted inline script');
</script>
Attach the per-request nonce to res.locals so your view template can inject it into trusted script elements.
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' https:; object-src 'none'; base-uri 'none';`
);
next();
});
Requires --with-http_ssl_module and --with-http_sub_module. Disable upstream compression so sub_filter can rewrite HTML, never leak $request_id elsewhere, and skip pages reflecting unescaped user input.
proxy_set_header Accept-Encoding "";
add_header Cache-Control "private, no-store" always;
add_header Content-Security-Policy "script-src 'nonce-$request_id' 'strict-dynamic' https:; object-src 'none'; base-uri 'none';" always;
sub_filter_once off;
sub_filter '__CSP_NONCE__' $request_id;
Safe only for trusted static builds (for dynamic HTML, generate nonces in your app). Guards text/html, clones headers, and sets Cache-Control: private, no-store.
export default {
async fetch(request) {
const res = await fetch(request);
const ct = (res.headers.get('content-type') || '').toLowerCase();
if (!ct.includes('text/html') || !res.body) return res;
const bytes = crypto.getRandomValues(new Uint8Array(16));
const nonce = btoa(String.fromCharCode(...bytes));
const headers = new Headers(res.headers);
headers.set(
'Content-Security-Policy',
`script-src 'nonce-${nonce}' 'strict-dynamic' https:; object-src 'none'; base-uri 'none';`
);
headers.set('Cache-Control', 'private, no-store');
const wrapped = new Response(res.body, { status: res.status, statusText: res.statusText, headers });
return new HTMLRewriter()
.on('script', { element(el) { el.setAttribute('nonce', nonce); } })
.transform(wrapped);
}
};
CSP nonce vs hash vs unsafe-inline
Choose a CSP strategy based on whether HTML is rendered per request or cached on a CDN.
| Method | Static / CDN | Inline scripts | Security | Best fit |
|---|---|---|---|---|
'nonce-...' |
No (per request) | Yes (matching nonce) | High (single-use) | PHP, Node, Python, and SSR apps |
'sha256-...' |
Yes (fixed bytes) | Yes (exact hash) | High (exact bytes) | Static sites and CDN-cached HTML |
'unsafe-inline' |
Yes | All inline (unsafe) | Low (no XSS defense) | Legacy fallback (ignored with nonce/hash) |
| Host allowlist | Yes | External origins only | Medium (JSONP risk) | Apps with zero inline script or style tags |
Best practices
- Generate a fresh, random
nonceon the server for every page response. - Match the nonce in both the CSP header and the element.
- Prefer external files over inline code where you can, reducing the need for nonces.
- Never reuse a nonce across requests; it must be unguessable and single-use.
Browser compatibility
Core CSP Level 2 nonces shipped across browsers by Edge 79 (January 2020), and CSP Level 3 ('strict-dynamic'), el.nonce, and attribute hiding all landed by Safari 15.5 (May 2022).
| Feature | Chrome | Edge | Firefox | Safari |
|---|---|---|---|---|
nonce on <script> & <style>EdgeHTML 15-18 had partial support |
ChromeSupported since 40+ | EdgeSupported since 79+ | FirefoxSupported since 31+ | SafariSupported since 10+ |
el.nonce DOM property |
ChromeSupported since 61+ | EdgeSupported since 79+ | FirefoxSupported since 75+ | SafariSupported since 15.4+ |
Hide nonce from CSS & getAttribute()Prevents CSS attribute-selector exfiltration |
ChromeSupported since 61+ | EdgeSupported since 79+ | FirefoxSupported since 75+ | SafariSupported since 15.5+ |
Frequently asked questions
What does the nonce attribute do?
How do I generate a nonce?
Content-Security-Policy header as 'nonce-VALUE' and echo the same value in the nonce attribute of each trusted inline script or style.Can I hard-code a nonce?
Is nonce a global attribute?
Why does element.getAttribute("nonce") return an empty string?
nonce content attribute from getAttribute("nonce"), CSS attribute selectors, and DOM serialization (innerHTML) to block non-script side-channel leaks such as injected CSS selectors (script[nonce^="a"]) or dangling markup. Scripts running in the page can still read the token via the element.nonce DOM property.Can I use a CSP nonce on static or CDN-cached HTML?
sha256 script hashes for static HTML, or inject a fresh nonce per request at the edge (for example, with Cloudflare Workers and HTMLRewriter on trusted static builds).






















