Implement strict Content-Security-Policy (CSP) Level 3 nonces across Drupal while preserving 100% Internal Page Cache, Dynamic Page Cache, and Varnish hit ratios.
Standard enterprise security policies (such as PCI-DSS v4.0 Requirement 6.4.3,
HIPAA, and SOC 2) require modern web applications to enforce strict,
randomized 'nonce-...' tokens on all <script> and <style>
elements while completely banning 'unsafe-inline'.
However, generating a dynamic cryptographic nonce inside Drupal's PHP runtime (for example, in a theme's
hook_preprocess_html() or hook_page_attachments()) introduces severe architectural
consequences:
CF_EDGE_NONCE) in its compiled Twig
templates and page attachments. Drupal's Internal Page Cache and Varnish cache the rendered HTML at
100% efficiency. As the cached HTML passes through Cloudflare Edge, EdgeNonce streams
in a fresh 128-bit cryptographic nonce on-the-fly in under 1.5ms.
The recommended architecture places EdgeNonce at the CDN edge tier in front of your Drupal caching layers:
Drupal renders static placeholder tokens. Varnish and Drupal Internal Page Cache preserve 100% cache hit rates. Cloudflare Worker replaces the placeholder and attaches strict headers.
Create a lightweight custom module in your Drupal project under modules/custom/edgenonce. This
module injects the <meta name="csp-nonce" content="CF_EDGE_NONCE"> header and securely
attaches the compatibility library.
modules/custom/edgenonce/edgenonce.info.ymlname: 'EdgeNonce CSP Bridge'
type: module
description: 'Integrates Drupal with EdgeNonce zero-latency edge streaming nonce injection.'
package: Security
core_version_requirement: ^9 || ^10 || ^11
dependencies:
- drupal:core
modules/custom/edgenonce/edgenonce.module<?php
/**
* @file
* Primary module hooks for EdgeNonce CSP Bridge.
*/
use Drupal\Core\Render\Markup;
/**
* Implements hook_page_attachments().
* Injects static placeholder meta tag and CSP compatibility bridge.
*/
function edgenonce_page_attachments(array &$attachments) {
// 1. Meta tag for client-side scripts to read the request nonce
$attachments['#attached']['html_head'][] = [
[
'#tag' => 'meta',
'#attributes' => [
'name' => 'csp-nonce',
'content' => 'CF_EDGE_NONCE',
],
],
'edgenonce_meta_nonce',
];
// 2. Attach EdgeNonce Client Compatibility Suite (csp-compat.js)
$attachments['#attached']['library'][] = 'edgenonce/csp_compat';
}
/**
* Implements hook_preprocess_html().
* Ensures all script tags rendered by Drupal carry the static placeholder.
*/
function edgenonce_preprocess_html(&$variables) {
// Pass nonce placeholder to window scope for JavaScript applications
$variables['#attached']['drupalSettings']['edgeNonce'] = [
'placeholder' => 'CF_EDGE_NONCE',
];
}
modules/custom/edgenonce/edgenonce.libraries.ymlcsp_compat:
header: true
js:
https://edge-nonce.com/assets/js/csp-compat.prod.js:
type: external
minified: true
attributes:
nonce: 'CF_EDGE_NONCE'
defer: true
# Using Drush (Drupal CLI)
drush pm:enable edgenonce -y
drush cache:rebuild
If your Drupal architecture utilizes a custom theme rather than custom modules, you can configure your
theme's html.html.twig template directly:
themes/custom/your_theme/templates/html.html.twig<!DOCTYPE html>
<html{{ html_attributes }}>
<head>
<head-placeholder token="{{ placeholder_token }}">
<!-- EdgeNonce Meta Nonce Tag for Client Scripts -->
<meta name="csp-nonce" content="CF_EDGE_NONCE">
<title>{{ head_title|safe_join(' | ') }}</title>
<css-placeholder token="{{ placeholder_token }}">
<js-placeholder token="{{ placeholder_token }}">
<!-- EdgeNonce Compatibility Bridge -->
<script src="https://edge-nonce.com/assets/js/csp-compat.prod.js" nonce="CF_EDGE_NONCE" defer></script>
</head>
<body{{ attributes }}>
{{ page_top }}
{{ page }}
{{ page_bottom }}
<js-bottom-placeholder token="{{ placeholder_token }}">
</body>
</html>
Drupal core includes the BigPipe module (big_pipe) for sending personalized
content chunks over chunked HTTP streaming responses.
When BigPipe renders dynamic content, it emits
<script type="application/json" data-big-pipe-replacement-for-placeholder-with-id="...">
tags into the stream.
injectIntoAllScripts: true to guarantee that BigPipe and lazy-loaded AJAX script tags
automatically receive dynamic nonces.To prevent your origin Varnish or Nginx cache from being bypassed, ensure backend CSP headers generated by Drupal or webserver default configs are stripped before reaching the edge CDN.
/etc/varnish/default.vclsub vcl_backend_response {
# Unset origin CSP header so Cloudflare Worker acts as the single authoritative policy source
unset beresp.http.Content-Security-Policy;
unset beresp.http.X-Content-Security-Policy;
# Allow Drupal's static HTML with CF_EDGE_NONCE to cache for anonymous visitors
if (beresp.status == 200 && beresp.http.content-type ~ "text/html") {
set beresp.ttl = 1d;
set beresp.grace = 6h;
}
}
/etc/nginx/conf.d/drupal.conflocation ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# FastCGI Page Caching for Anonymous Traffic
fastcgi_cache DRUPAL_CACHE;
fastcgi_cache_valid 200 301 302 1d;
fastcgi_cache_use_stale error timeout updating invalid_header http_500;
# Hide backend CSP headers to prevent duplication with edge worker
fastcgi_hide_header Content-Security-Policy;
}
csp-compat.js
Under Strict CSP Level 3, inline event attributes like onclick="..." and inline
style="..." are blocked by default.
Drupal contributed modules and custom templates can use EdgeNonce's drop-in attributes:
| Legacy Drupal Syntax (Blocked) | EdgeNonce Compliant Syntax (Allowed) |
|---|---|
| <button onclick="myFunction()"> | <button data-evt-click="myFunction"> |
| <div style="display:none;"> | <div data-style="display:none;"> |
| <input onchange="submitForm(this.value)"> | <input data-evt-change="submitForm(this.value)"> |
After enabling the module and rebuilding your Drupal cache, verify edge injection using curl:
# 1. Verify that Cloudflare returns a valid 128-bit CSP nonce header
curl -I https://www.yourdrupalsite.com/ \
-H "User-Agent: Mozilla/5.0"
# Output should include:
# content-security-policy: script-src 'self' 'nonce-a4f9b2c8...' 'strict-dynamic' https:;
# x-edge-csp-status: active
# 2. Verify that HTML placeholders (CF_EDGE_NONCE) have been replaced
curl -s https://www.yourdrupalsite.com/ | grep "nonce=" | head -n 5
# Output should show real randomized nonces:
# <meta name="csp-nonce" content="a4f9b2c8...">
# <script nonce="a4f9b2c8..." src="..."></script>
When hosting Drupal on managed enterprise cloud platforms such as Acquia Cloud or Pantheon, caching layers must be configured so that upstream Varnish instances cache pages containing the static CF_EDGE_NONCE placeholder rather than bypassing cache or regenerating tokens per-request.
Acquia Cloud terminates requests through dedicated Balancers and Varnish instances. Add the following block to your docroot/sites/default/settings.php (or settings.acquia.php) to ensure Acquia Varnish caches HTML with the EdgeNonce placeholder while Cloudflare Workers stream unique nonces to end users:
<?php
/**
* EdgeNonce Integration for Acquia Cloud Platform
* Automatically activates on Acquia Dev, Stage, and Production tiers.
*/
if (isset($_ENV['AH_SITE_ENVIRONMENT'])) {
$env = $_ENV['AH_SITE_ENVIRONMENT'];
// 1. Maintain 100% Acquia Varnish HTML caching
$config['system.performance']['cache']['page']['max_age'] = 86400; // 24 hours
$config['system.performance']['css']['preprocess'] = TRUE;
$config['system.performance']['js']['preprocess'] = TRUE;
// 2. Prevent PHP origin from sending conflicting CSP headers
// Let Cloudflare Workers inject the authoritative W3C CSP Level 3 header
$settings['edgenonce_origin_csp_disabled'] = TRUE;
// 3. Ensure Acquia Purge module invalidates Cloudflare Edge cache when content updates
if ($env === 'prod') {
$settings['acquia_purge_cloudflare_sync'] = TRUE;
}
}
acquia_purge module purges Acquia Varnish instantly. Cloudflare Cache Purge API clears the edge cache, immediately fetching fresh HTML containing CF_EDGE_NONCE without cache misses.
Pantheon utilizes an internal Global CDN powered by Fastly before routing to application containers. Add this recipe to sites/default/settings.php (or settings.pantheon.php):
<?php
/**
* EdgeNonce Integration for Pantheon Platform
* Detected via PANTHEON_ENVIRONMENT (dev, test, live).
*/
if (isset($_ENV['PANTHEON_ENVIRONMENT'])) {
// 1. Set Surrogate-Control and Cache-Control headers for Pantheon edge
$settings['cache']['page']['max_age'] = 86400;
// 2. Trust Cloudflare upstream proxy SSL termination
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
$_SERVER['HTTPS'] = 'on';
$_SERVER['SERVER_PORT'] = 443;
}
// 3. Tell Pantheon upstream Fastly proxy to cache anonymous responses
$settings['reverse_proxy'] = TRUE;
$settings['reverse_proxy_addresses'] = [$_SERVER['REMOTE_ADDR']];
}
EdgeNonce is CMS-agnostic. In addition to Adobe AEM and Drupal, teams running headless or hybrid architectures can deploy EdgeNonce across WordPress and Next.js frontends:
Drop this Must-Use (MU) plugin into wp-content/mu-plugins/edgenonce.php. It automatically hooks into WordPress script enqueues and outputs CF_EDGE_NONCE placeholders without triggering PHP cache invalidation in WP Rocket, W3 Total Cache, or Batcache:
<?php
/**
* Plugin Name: EdgeNonce CSP Integration for WordPress
* Description: Injects CF_EDGE_NONCE placeholders into enqueued scripts, preserving 100% full-page static caching.
*/
add_filter('script_loader_tag', function($tag, $handle, $src) {
if (is_admin()) return $tag;
// Inject the EdgeNonce placeholder into all enqueued script tags
if (strpos($tag, 'nonce=') === false) {
return str_replace('<script ', '<script nonce="CF_EDGE_NONCE" ', $tag);
}
return $tag;
}, 10, 3);
// Output CSP Nonce meta tag in head
add_action('wp_head', function() {
echo '<meta name="csp-nonce" content="CF_EDGE_NONCE">' . "\n";
}, 1);
In Next.js App Router (13/14/15), configure middleware.ts to emit the static placeholder during Static Site Generation (SSG) or Incremental Static Regeneration (ISR). Cloudflare Workers replace the placeholder in under 1.5ms at the edge:
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
const requestHeaders = new Headers(request.headers);
// Forward placeholder header to downstream React Server Components
requestHeaders.set('x-nonce', 'CF_EDGE_NONCE');
const response = NextResponse.next({
request: { headers: requestHeaders }
});
return response;
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
Our security and edge computing engineers provide turnkey integration assistance for Drupal multi-site multisites, Acquia Cloud, Pantheon, and custom Varnish clusters.
✉️ Contact Enterprise Team: contact@edge-nonce.com