This project is not covered by Drupal’s security advisory policy.

Nonce Generator

Generates fresh CSP nonces per request and automatically injects them into script-src Content Security Policy headers.

What It Does

This module generates a unique nonce for each HTTP request and automatically adds it to your CSP headers. The module itself doesn't add any scripts — you create plugins to output scripts that use the nonce.

How it works

  • Scripts get fresh nonces on every request via lazy builders
  • No CSP violations even with cached content

Creating a Plugin

Create a plugin class in your module at src/Plugin/NonceScript/MyScript.php:

<?php

namespace Drupal\mymodule\Plugin\NonceScript;

use Drupal\nonce_generator\Plugin\NonceScript\NonceScriptPluginBase;

/**
 * @NonceScript(
 *   id = "my_script",
 *   label = @Translation("My Script")
 * )
 */
class MyScript extends NonceScriptPluginBase {

  public function getScript(string $nonce): string {
    $escaped_nonce = htmlspecialchars($nonce, ENT_QUOTES, 'UTF-8');

    return <<<SCRIPT
<script type="text/javascript" nonce="{$escaped_nonce}">
console.log("Hello from my script!");
// Add more JavaScript here
</script>
SCRIPT;
  }
}

Adding to Templates

Use in render arrays or templates:

// Render a specific plugin
$build['my_script'] = [
  '#type' => 'nonce_script',
  '#plugin_id' => 'my_script',
];

// Render all active plugins
$build['all_scripts'] = [
  '#type' => 'nonce_script',
  '#all_plugins' => TRUE,
];
Supporting organizations: 

Project information

Releases