{nonce}

This request's Content-Security-Policy nonce, for a script or style the policy lets run.

Forms and security Single tags

Syntax

{nonce}

Description

{nonce} answers this request's nonce: 18 random bytes, base64 - one value for the whole request, made on first use. Put it on the scripts and styles the page itself writes: <script nonce="{nonce}">.

The engine puts the same value in the Content-Security-Policy header: 'nonce' (quotes included) in $padCsp becomes 'nonce-<the value>', so $padCsp = "default-src 'self'; script-src 'self' 'nonce'" lets exactly the scripts that carry it run - an injected script cannot know the value. The engine never adds it to script tags by itself, except to the scripts it writes, such as {validator}'s.

Write it outside an {ignore} pair: inside one it is text. The value is new on every request, so a page carrying a nonce is never stored in the page cache, and the examples here are shown, not run.

Examples

A script the policy lets run

The nonce on the script tag is the one in this response's Content-Security-Policy header - a script without it is blocked.

Templateexamples/nonce/1-script.src
{# _config/config.php: $padCsp = "default-src 'self'; script-src 'self' 'nonce'"; #}
<script nonce="{nonce}">{ignore}
  document.documentElement.classList.add('js');
{/ignore}</script>

{# renders: <script nonce="kq3Z0d9wQ1m2bH8sVf7aXyPc"> - a new value every request #}

One value for the whole request

Every {nonce} of a request answers the same value, so a style and a script share it.

Templateexamples/nonce/2-style.src
<style nonce="{nonce}">{ignore}
  .banner { color: #b00; }
{/ignore}</style>
<script nonce="{nonce}" src="app.js"></script>

See also

  • {csrf} The hidden form field holding the CSRF token of the visitor's session, or the bare token.
  • {asset} The address of a file of www/<app>/ with a version of its contents, safe behind a far-future cache header.
  • {validator} The browser's checker of the validation rules as one inline script, for a form a component draws.