🔧 CSP Nonce Generator for AdSense
Why This Matters — The May 16, 2026 Deadline
Starting May 16, 2026, Google AdSense will require all publisher
sites to implement a Content Security Policy (CSP) that uses nonce-based script authorization.
This means the old approach of using 'unsafe-inline' in your CSP headers will no longer be
accepted. Every page that serves AdSense ads must generate a unique, cryptographically random nonce
per HTTP request, inject it into both the CSP response header and the AdSense <script> tag,
and ensure no other inline scripts run without a valid nonce.
For sites running on Cloudflare Workers, this is straightforward to implement because the
Worker runtime provides crypto.randomUUID() and you have full control over both the HTML body
and the response headers. The template below gives you a complete, copy-paste-ready Worker that handles the
entire flow — nonce generation, header injection, and script tag annotation.
Failure to comply by the deadline may result in ad serving being paused on your site, directly impacting your AdSense revenue. We strongly recommend implementing this change well ahead of May 16.
Cloudflare Worker Template
Copy this template and replace ca-pub-YOUR_ID with your actual AdSense publisher ID:
export default {
async fetch(request) {
// 1. Generate a unique nonce per request
const nonce = crypto.randomUUID();
// 2. Fetch or build your HTML response
const html = \`<!DOCTYPE html>
<html>
<head>
<script nonce="\${nonce}" async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-YOUR_ID"
crossorigin="anonymous"><\/script>
</head>
<body>
<h1>Hello, CSP-compliant world!</h1>
</body>
</html>\`;
// 3. Return response with CSP header
return new Response(html, {
headers: {
"Content-Type": "text/html;charset=UTF-8",
"Content-Security-Policy":
\`script-src 'self' 'nonce-\${nonce}' https://pagead2.googlesyndication.com;\`
},
});
},
};
How It Works
- Nonce Generation:
crypto.randomUUID()produces a unique v4 UUID for every incoming request. This ensures each page load has its own nonce, preventing replay attacks. - Header Injection: The
Content-Security-Policyheader whitelists only scripts that carry the matching nonce, plus the AdSense syndication domain. - Script Tag: The
nonceattribute on the AdSense script tag tells the browser this specific script is authorized under the CSP policy.