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 stop scripts from stealing it.
Values
| Value |
|---|
| A random, single-use, base64 token generated per request. |
Example
<!-- Server sends: Content-Security-Policy: script-src 'nonce-r4nd0m' -->
<script nonce="r4nd0m">/* this inline script is allowed */</script>
Best practices
- Generate a fresh, random nonce on 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.