Ad code & integration

AdSense with a Content Security Policy: the strict, nonce-based setup Google supports

Last updated Published By the editorial team6 min4 sources

Key takeaways

  • Publishers are not required to use a Content Security Policy, but if they do, AdSense supports only strict CSP based on a random nonce, not a domain allowlist.
  • Google gives a supported policy: object-src 'none', a script-src with a nonce, 'unsafe-inline', 'unsafe-eval', 'strict-dynamic', https: and http:, and base-uri 'none'.
  • Every script tag, including the adsbygoogle.js loader and the inline push call, must carry the nonce of the current response.
  • Google states that more restrictive policies may break without notice, and that failing to follow its CSP guidance may disrupt ad serving.
  • Test first with the Content-Security-Policy-Report-Only header, which reports violations without blocking anything.
A red stop sign at a street corner in Toronto
Image: Stop sign in Toronto, Canada,Katarighe .,CC BY-SA 3.0,via Wikimedia Commons.

You do not need a Content Security Policy to run AdSense. If you use one, Google supports only a strict CSP built on a random nonce: every <script> tag, including the AdSense loader and the inline push() call, carries the nonce generated for that response, and the policy uses 'strict-dynamic'. Domain allowlists are not supported, because the hosts the ad code uses change over time.

What does Google support?

Google’s article Integrate the AdSense ad code with a Content Security Policy starts with two points worth quoting:

  • “publishers are not required to use CSP.”
  • “You must update your site’s CSP to comply with our documented guidance. Failure to do so may result in a disruption of ad serving on your site.”

It then compares the two usual ways to write a CSP: a list of allowed domains, or a random nonce that every script must carry, known as strict CSP. Google’s position: “Because the domains that the AdSense ad code uses change over time, we only support strict CSP (option 2).”

The directives Google says the AdSense code supports:

Content-Security-Policy:
    object-src 'none';
    script-src 'nonce-{random}' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:;
    base-uri 'none';
    report-uri https://your-report-collector.example.com/

Google adds: “You can choose a more permissive policy if it fits your use case. More restrictive policies may break without notice.”

What does each part do?

Directive or keyword Role Source
'nonce-{random}' Only scripts with this nonce attribute run web.dev strict CSP
'strict-dynamic' Scripts loaded by a trusted (nonced) script are trusted too, which lets adsbygoogle.js load what it needs MDN, web.dev
https: http: Fallback for browsers without 'strict-dynamic'; browsers that support it ignore these web.dev
'unsafe-inline' Fallback for very old browsers; ignored when a nonce or hash is present MDN, web.dev
'unsafe-eval' Allows eval()-style code; unlike 'unsafe-inline', it still applies next to a nonce MDN
object-src 'none' Blocks plugins such as <object> and <embed> web.dev
base-uri 'none' Blocks <base> tag injection web.dev
report-uri Where browsers send violation reports Google, MDN

Notice what is absent: no default-src, img-src, frame-src or connect-src. Adding a default-src 'self' line is the most common way to turn this policy into a “more restrictive” one, because it then restricts images, frames and network requests that ads rely on. If you need those directives for your own content, keep them permissive enough for ads and test in report-only mode first.

How do I add the nonce to the AdSense code?

Google’s example, adapted with placeholders:

<script nonce="RANDOM_NONCE" async
        src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-0000000000000000"
        crossorigin="anonymous"></script>

<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-0000000000000000"
     data-ad-slot="1234567890"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script nonce="RANDOM_NONCE">
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Both script tags carry the nonce, exactly as in Google’s own example. Google’s sample also uses a protocol-relative //pagead2... URL; keeping the full https:// URL from your generated code is fine, since 'strict-dynamic' trusts the tag through its nonce, not its URL.

The nonce itself must follow the rules in web.dev’s strict CSP guide: “A cryptographically strong random value (ideally 128+ bits in length)”, “Newly generated for every response”, and base64 encoded. A minimal Node.js example with Express:

import crypto from "node:crypto";
import express from "express";

const app = express();

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString("base64");
  res.locals.nonce = nonce;
  res.setHeader(
    "Content-Security-Policy",
    `object-src 'none'; ` +
    `script-src 'nonce-${nonce}' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:; ` +
    `base-uri 'none'`
  );
  next();
});

Your templates then print res.locals.nonce into each nonce attribute.

How does this work in frameworks?

Next.js. The Next.js CSP guide generates the nonce in proxy.ts, sets the header, and passes the value in an x-nonce request header. Next.js then applies the nonce to its own scripts and to <Script> components that receive the nonce prop. The guide warns that “you must use dynamic rendering to add nonces”: statically generated pages cannot get a per-request nonce. The AdSense in Next.js guide shows the layout code.

Static site generators (Astro, Hugo, Eleventy). A nonce written into HTML at build time is the same for every visitor, which defeats its purpose. You need something that runs per request, such as an edge function or a server in front of the static files, to generate the nonce, set the header and rewrite the nonce attributes. web.dev recommends hash-based CSP for static pages, but Google’s AdSense article documents only the nonce approach, so a hash-only policy is outside what Google says it supports. See AdSense in Astro for the layout side.

Single-page apps. 'strict-dynamic' lets the nonced loader insert ad iframes and scripts after client-side navigations; the push call for new slots must come from your own nonced bundle, not from injected inline scripts. The single-page apps guide covers when to push.

How do I test before enforcing?

Google recommends testing with the Content-Security-Policy-Report-Only header first: it “reports violations but still allows them on the page”. A rollout plan:

  1. Send the policy as Content-Security-Policy-Report-Only with a report-uri you can read.
  2. Load pages with ads on mobile and desktop, including overlay formats (anchor, vignette) and pages with several units.
  3. Read the browser console and your reports. Violations from your own inline handlers (onclick="...") or javascript: links need refactoring, as web.dev describes.
  4. Switch the header name to Content-Security-Policy once reports are clean.
  5. Keep reporting on. A change in the ad code that your policy blocks shows up there before revenue drops.

web.dev notes that CSP <meta> tags do not support report-only mode, and it recommends the HTTP header over the meta tag. If your host only lets you add a meta tag, you cannot test this way.

report-uri or report-to?

Google’s sample policy uses report-uri. MDN describes that directive as deprecated and recommends the Reporting API instead: declare an endpoint in a Reporting-Endpoints header and point the policy’s report-to directive at it. MDN adds that “you should declare both until report-to is supported in all browsers”:

Reporting-Endpoints: csp-endpoint="https://reports.example.com/csp"
Content-Security-Policy-Report-Only: object-src 'none'; script-src 'nonce-RANDOM_NONCE' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:; base-uri 'none'; report-uri https://reports.example.com/csp; report-to csp-endpoint

MDN also notes that when both a Content-Security-Policy and a Content-Security-Policy-Report-Only header are present, “both policies are honored”. That lets you keep enforcing your current policy while testing a stricter candidate in report-only mode.

Automated checks help here. web.dev mentions that Lighthouse’s Best Practices audit can check whether a page has a CSP and whether it is strict enough to be effective against XSS; running it in CI catches regressions, see Lighthouse CI for ad pages.

Troubleshooting

Symptom Likely cause Fix
Console: “Refused to load the script … adsbygoogle.js” Loader tag has no nonce, or a stale one Print the current response’s nonce on the tag
Loader runs but slots stay empty Inline push() script blocked (no nonce) Add the nonce to the inline script, or push from your nonced bundle
Ads worked, then stopped after a policy change default-src, frame-src or connect-src added Remove them or loosen them; Google says stricter policies may break
Every page shows the same nonce Nonce generated at build time or cached HTML Generate per response and avoid caching the HTML with the nonce
Consent banner or CMP stops working Its scripts lack the nonce Nonce every script tag, including your certified CMP

Common mistakes

  • Writing an allowlist of Google ad domains. Google does not support it, and it will break as domains change.
  • Dropping 'unsafe-eval' to “harden” the policy. That is a more restrictive policy than Google documents, which “may break without notice”.
  • Caching full HTML pages with a nonce in them. A CDN that serves the same HTML to everyone serves the same nonce. Generate the nonce at the edge or bypass caching for HTML.
  • Forgetting third-party tags. Analytics, the CMP and any other loader must carry the nonce too.

Frequently asked questions

Do I need a Content Security Policy to use AdSense?

No. Google's CSP article states that publishers are not required to use CSP. It only matters if your site already sends a Content-Security-Policy header, or you plan to add one for security reasons. In that case, the policy must follow Google's strict, nonce-based guidance, or ad serving may be disrupted.

Can I allowlist pagead2.googlesyndication.com instead of using a nonce?

Google says no. Its article explains that the domains used by the AdSense code change over time, so it only supports strict CSP with a random nonce. An allowlist that works today could break later without warning when the ad code starts loading resources from a host you did not list.

Why does Google's AdSense policy include 'unsafe-inline' and 'unsafe-eval'?

Google lists them in the directives the AdSense code supports, without explaining why. MDN notes that browsers ignore 'unsafe-inline' when a nonce or hash is present, so it only acts as a fallback for old browsers. 'unsafe-eval' keeps working alongside a nonce. If you remove it, you run a more restrictive policy, which Google says may break without notice.

Can a static site use AdSense with a strict CSP?

Only if something generates a fresh nonce for every response, because a nonce baked into a static file is the same for everyone and can be guessed. On static hosting, that means an edge function or server that rewrites the header and the nonce attributes on each request. web.dev suggests hashes for static pages, but Google's AdSense article documents only the nonce approach.

Sources

  1. Integrate the AdSense ad code with a Content Security Policy (CSP) · Google AdSense Help
  2. Mitigate cross-site scripting (XSS) with a strict Content Security Policy (CSP) · web.dev
  3. Content Security Policy (CSP) · MDN Web Docs
  4. How to set a Content Security Policy (CSP) for your Next.js application · Next.js Docs