References

Beginner-friendly references for web development, with live, editable examples.

The HTML nonce attribute

Global attribute Works on every element All modern browsers Updated
Quick answer

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

Live 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.

Frequently asked questions

What does the nonce attribute do?
A single-use cryptographic token a Content-Security-Policy uses to allow a specific inline script or style.
What is a nonce used for?
It lets a specific inline <script> or <style> run under a strict Content-Security-Policy that otherwise blocks inline code.
Can I hard-code a nonce?
No. It must be randomly generated per response and matched in the CSP header, or it provides no security.
Is nonce a global attribute?
Yes — it is a global attribute, so it can be set on any HTML element (it is a global attribute), in practice <script> and <style>.