Gitea Custom Template Inline Scripts Blocked by CSP Nonce

Contents

Symptom

After putting the Matomo tracking script into $GITEA_CUSTOM/templates/custom/header.tmpl (rendered before the closing </head> tag), no statistics show up on the site. The browser console reports:

Executing inline script violates the following Content Security Policy directive 'script-src * 'nonce-<random>''. Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.

Cause

Gitea 1.27.0 switched its CSP inline-script policy to a per-request nonce (PR #37232): a random nonce is generated per response and script-src becomes * 'nonce-xxx': external scripts still load, but inline <script> tags only execute when they carry that nonce. Inline scripts in custom templates have no nonce attribute, so the browser blocks them. The 1.27.0 release notes mention this too: inline <script> tags injected by custom templates stop executing until they are updated to carry the nonce.

Fix

Add a nonce attribute to the script tag, using the template variable {{ctx.CspScriptNonce}}:

<script nonce="{{ctx.CspScriptNonce}}">
  // your inline script, e.g. Matomo tracking code
</script>

After saving, restart Gitea (just restart the container for container deployments) and refresh the page: the console no longer reports CSP blocking errors, and visitors show up in the statistics dashboard.

Contents