HTML nonce Attribute

Beginner
⏱️ 7 min read
📚 Updated: Jun 2026
🎯 3 Examples
Security & CSP

Introduction

The nonce attribute holds a one-time token (number used once) on trusted inline <script> and <style> elements. It works together with Content Security Policy (CSP)—not on its own. When your server sends a header like Content-Security-Policy: script-src 'nonce-abc123', the browser runs only inline scripts whose nonce attribute matches that value. Injected attacker scripts without the correct nonce are blocked. This tightens CSP compared to allowing all inline code with 'unsafe-inline'.

What You’ll Learn

01

CSP partner

Needs policy header.

02

script & style

Inline tags.

03

Server token

Random per page.

04

Match rule

nonce = CSP value.

05

vs unsafe-inline

Tighter control.

06

.nonce JS

Read property.

Purpose of nonce Attribute

The primary purpose of nonce is to let you use a strict CSP that blocks most inline JavaScript and CSS while still allowing specific trusted inline blocks your server placed in the HTML. Cross-site scripting (XSS) attacks often inject new <script> tags; those injected tags will not have the secret nonce value generated for that response, so CSP refuses to execute them.

The server generates a fresh random nonce for every page load, puts the same value in the CSP header (as 'nonce-VALUE') and in the nonce attribute on each allowed inline <script> or <style>. External scripts loaded from allowed origins use script-src https://cdn.example.com instead—they do not need a nonce attribute.

⚠️
nonce alone does nothing

Adding nonce="ABC123" without a matching CSP policy does not improve security. The browser enforces nonces only when CSP includes 'nonce-ABC123' in script-src or style-src.

📝 Syntax

Server sets CSP header and matching nonce on inline resources:

nonce.html
<!-- HTTP response header (set by server) -->
Content-Security-Policy: script-src 'nonce-r4nd0m'; style-src 'nonce-r4nd0m'

<script nonce="r4nd0m">
  initDashboard();
</script>

<style nonce="r4nd0m">
  .hero { color: navy; }
</style>

<!-- No nonce — blocked when CSP is strict -->
<script>alert("blocked");</script>

Syntax Rules

  • Value is an opaque string; CSP uses 'nonce-VALUE' (with quotes in the header).
  • Generate a new unpredictable value on every HTTP response—never reuse across users or pages.
  • Valid on <script>, <style>, and <link> (stylesheet).
  • External scripts from allowed hosts do not use nonce—they rely on host allowlists.
  • JavaScript IDL property: scriptElement.nonce returns the attribute value.
  • Set server-side in HTML templates; client-side assignment does not satisfy CSP for inline scripts.

💎 Values

The nonce attribute accepts a single token string:

  • nonce="r4nd0mToken" — Must match 'nonce-r4nd0mToken' in CSP.
  • Use cryptographically secure random bytes (e.g. 16+ bytes, base64-encoded).
  • Same nonce can appear on multiple trusted inline tags in one response.
  • Do not expose the nonce in URLs or logs unnecessarily.
  • JavaScript: element.nonce reads the value; avoid writing it from untrusted scripts.
nonce-server.js
// Node.js example — generate per request
const crypto = require("crypto");
const nonce = crypto.randomBytes(16).toString("base64");

res.setHeader(
  "Content-Security-Policy",
  "script-src 'nonce-" + nonce + "'; style-src 'nonce-" + nonce + "'"
);

// Pass nonce into HTML template for script/style tags

⚡ Quick Reference

Use caseMarkup / headerNotes
Allow inline scriptscript-src 'nonce-X' + <script nonce="X">Values must match
Allow inline stylestyle-src 'nonce-X' + <style nonce="X">Same pattern
External scriptscript-src https://cdn.example.comNo nonce on src scripts
Read in JSdocument.querySelector("script").nonceIDL property
Meta CSP (demo)<meta http-equiv="Content-Security-Policy" …>Prefer HTTP header
Block all inlinescript-src 'self' (no nonce, no unsafe-inline)Strictest scripts

Applicable Elements

ElementSupported?Notes
<script>YesInline scripts under CSP
<style>YesInline CSS under CSP
<link rel="stylesheet">YesWhen stylesheet needs nonce
<div>, <meta>NoNot valid for nonce

nonce vs 'unsafe-inline' vs hash

CSP approachAllowsSecurity
'nonce-…' + HTML nonceSpecific inline scripts/styles you tagStrong (if nonce is secret per response)
'sha256-…' hashExact inline content matching hashStrong; no per-request randomness
'unsafe-inline'All inline scripts/stylesWeak; XSS can inject inline code

Examples Gallery

Inline script with CSP, inline style with CSP, and reading script.nonce from server-rendered markup.

👀 Live Preview

CSP via meta tag allows only the script with a matching nonce:

Trusted script output appears here.

This page demo uses a fixed nonce. Production sites generate a new value per request.

Example — Inline Script with CSP

Matching CSP header and script nonce:

script-nonce.html
<meta http-equiv="Content-Security-Policy"
      content="script-src 'nonce-trusted123'">

<script nonce="trusted123">
  initApp();
</script>

<script>evil();</script> <!-- blocked -->
Try It Yourself

How It Works

The browser compares each inline script’s nonce attribute against the 'nonce-…' entries in script-src. Only matching scripts execute. The old reference implied the attribute alone provides security—CSP enforcement is required.

Example — Inline Style with CSP

Apply the same pattern to inline CSS:

style-nonce.html
<meta http-equiv="Content-Security-Policy"
      content="style-src 'nonce-style789'">

<style nonce="style789">
  .card { border-radius: 8px; }
</style>
Try It Yourself

How It Works

style-src 'nonce-…' in CSP whitelists specific inline style blocks. This prevents injected <style> tags from applying unless the attacker knows the per-response nonce.

Reading script.nonce in JavaScript

Read the server-provided nonce from the DOM (do not set it client-side for CSP):

read-nonce.html
<script id="boot" nonce="<%= serverNonce %>">
  console.log(document.getElementById("boot").nonce);
</script>
Try It Yourself

How It Works

Templates inject the same random nonce into the CSP header and HTML attributes. Client code may read element.nonce but should not rely on client-side generation for security enforcement.

♿ Accessibility

  • nonce is invisible to users — It does not affect screen readers or keyboard navigation directly.
  • Do not block critical UI scripts — Ensure CSP nonces cover accessibility helpers (skip links, focus management) your page needs.
  • Prefer external scripts — Moving logic to external files reduces inline CSP complexity and aids caching.
  • Test with CSP enabled — Verify assistive features still work under your production policy.
  • Avoid inline event handlersonclick="" attributes are blocked by strict CSP and are poor for accessibility; use addEventListener in nonce-approved or external scripts.

🧠 How nonce Works

1

Server generates token

Random nonce unique to this response.

Backend
2

CSP + HTML match

Header and nonce attributes use same value.

Policy
3

Browser enforces

Matching inline scripts/styles run; others blocked.

CSP
=

XSS mitigation

Injected inline code lacks the secret nonce.

Browser Support

The nonce attribute and CSP nonce source expressions are supported in Chrome 40+, Firefox 31+, Safari 10+, and Edge 15+. CSP itself is widely supported; always send the policy via HTTP response headers in production (meta tags are acceptable for demos only).

CSP · Modern browsers

CSP nonce in modern browsers

Chrome, Firefox, Safari, and Edge enforce nonce matching when Content-Security-Policy is set via headers.

95% Browser support
Google Chrome 40+
Full support
Mozilla Firefox 31+
Full support
Apple Safari 10+
Full support
Microsoft Edge 15+
Full support
Internet Explorer Not supported
No CSP nonce
Opera Fully supported
Full support
nonce attribute 95% supported

Bottom line: nonce + CSP is supported in all modern browsers. Prefer HTTP headers over meta CSP in production.

💡 Best Practices

✅ Do

  • Generate server-side — Use cryptographically secure random bytes per response; never hard-code demo values in production.
  • Send CSP via HTTP header — More reliable than <meta http-equiv> for real deployments.
  • Minimize inline code — Prefer external scripts; use nonce only where inline is unavoidable.
  • Include strict-dynamic carefully — Advanced CSP keywords like 'strict-dynamic' change how nonces propagate to dynamically loaded scripts.

❌ Don’t

  • Avoid 'unsafe-inline' — Nonces provide tighter control when you must allow some inline resources.
  • Do not leak the nonce — Avoid reflecting it in URLs, error messages, or publicly cacheable fragments attackers can read.
  • Hard-code demo nonce values in production — Generate a fresh cryptographically secure token on every response.

Conclusion

The nonce attribute tags trusted inline <script> and <style> elements with a one-time token that must match your Content-Security-Policy. It helps block XSS injection without opening the door to all inline code.

Always pair HTML nonces with a server-generated CSP header, rotate the value every response, and prefer external scripts when possible for simpler, safer deployments.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about nonce

Bookmark these before your next nonce implementation.

5
Core concepts
📄 02

script & style

Inline tags.

Scope
🌐 03

Server random

Per response.

Token
🚫 04

Blocks XSS

No matching nonce.

Defense
⚙️ 05

.nonce JS

Read only.

DOM

❓ Frequently Asked Questions

It marks inline <script> or <style> with a token that must match 'nonce-…' in your Content-Security-Policy for the browser to allow that inline resource.
No. The attribute alone does not block scripts. CSP must include a matching nonce source in script-src or style-src.
Your server generates a new cryptographically random value for each HTTP response and inserts it into both the CSP header and trusted HTML tags.
You can read element.nonce, but setting it client-side does not satisfy CSP for inline scripts already in the document. Generate nonces server-side.
No. External scripts are allowed via host sources like script-src https://cdn.example.com. Nonces apply to inline script and style content.
'unsafe-inline' allows all inline scripts (weak). Nonces allow only tagged inline resources (stronger when combined with strict CSP).

Secure inline scripts with nonce + CSP

Practice inline script blocking, style nonces, and reading script.nonce in the Try It editor.

Try CSP + nonce demo →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful