Skip to content

The publication for web craftspeople Friday, 4 December 2026

Security

Content Security Policy on WordPress with AdSense and GA4: a Policy That Doesn’t Break Anything

Building a Content Security Policy on a WordPress site that runs Google AdSense ads and tracks its audience with GA4 needs a different approach from a generic CSP. This guide covers the nonce-based policy Google recommends and how to implement it in…

Content Security Policy sur WordPress avec AdSense et GA4 : la politique qui ne casse rien
Photo : Pixabay / Pexels

A generic Content Security Policy (CSP), built around a fixed list of allowed domains, rarely survives on a WordPress site that runs Google AdSense ads and measures its audience with Google Analytics 4: both services load third-party scripts from domains that shift over time, and a frozen list either ends up blocking ads or becomes so permissive it stops protecting much of anything. For each of the two services, though, Google documents a precise policy built on a nonce — a random token generated on every page load — rather than on a domain list. This guide covers how to combine them on an existing WordPress site, without breaking either the ads or the audience measurement.

Why a generic CSP fails with AdSense and GA4

The step-by-step guide to Content Security Policy published here lays out the basics: start with Content-Security-Policy-Report-Only, restrict script-src to legitimate sources, ban 'unsafe-inline'. That approach works well for a site that controls every script it serves. It runs into two realities specific to advertising and audience measurement:

  • AdSense loads scripts from several Google domains that vary with whichever ad exchanges are involved at load time — Google states outright that “the domains AdSense uses change over time,” and so publishes no fixed allowlist.
  • GA4, through Google Tag Manager, injects further scripts itself depending on the tags configured in the container, which makes it impossible to predict everything that will need allowing in advance.

In both cases, Google recommends a so-called strict-dynamic policy, built on a nonce rather than a domain list: a script explicitly authorized by its nonce can then load other scripts dynamically, without having to enumerate every subdomain ahead of time.

The policy Google recommends for GTM and GA4

For Google Tag Manager and GA4 alone (without Google Ads), the official documentation gives this baseline:

DirectiveValue
script-src-elem'nonce-{NONCE}' https://www.googletagmanager.com
img-srchttps://www.googletagmanager.com https://*.google-analytics.com
connect-srchttps://www.googletagmanager.com https://*.google-analytics.com https://*.google.com

The nonce must be generated server-side on every HTTP response, never reused across pages, and carried over identically onto the GTM container’s <script> tag: Tag Manager then propagates that same nonce to the scripts it injects itself, with no extra configuration needed.

The strict policy Google recommends for AdSense

For AdSense, Google documents a more radical policy, built on 'strict-dynamic' rather than a domain:

Content-Security-Policy:
    object-src 'none';
    script-src 'nonce-{NONCE}' 'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:;
    base-uri 'none';

Having 'strict-dynamic' alongside 'unsafe-inline'/https: isn’t an inconsistency: browsers that understand 'strict-dynamic' ignore the fallback values ('unsafe-inline', https:, http:), which only serve older browsers. Every script on the page, including the AdSense loader and the inline script that calls adsbygoogle.push(), must carry the same nonce attribute. Google warns that tightening this policy beyond its own recommendations can break ad serving without notice.

Google publishes no domain list for AdSense because it keeps changing: the only policy it documents and stands behind is nonce-based, not an allowlist.

Combining both into a single header

Both policies share the same nonce and can merge into a single response header, keeping the strictness of the AdSense version while adding GA4’s own image and connection domains:

Content-Security-Policy-Report-Only:
    object-src 'none';
    base-uri 'none';
    script-src 'nonce-{NONCE}' 'strict-dynamic' 'unsafe-inline' https: http:;
    img-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https: data:;
    connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.google.com;
    report-uri https://example.com/wp-json/mailstudio/v1/csp-report

Keep this starting point in Report-Only until the testing phase is complete — see below for how to confirm no legitimate resource gets blocked before switching to an enforced policy.

Generating and injecting the nonce in WordPress

WordPress doesn’t natively generate an HTTP nonce for its security headers — the “nonce” term in the WordPress API refers to a different, form-specific mechanism. A small mu-plugin (must-use, loaded automatically with no activation step) is enough to generate a random nonce per request and attach it to every script:

<?php
// wp-content/mu-plugins/csp-nonce.php

add_action('send_headers', function () {
    if (is_admin()) {
        return;
    }
    $nonce = base64_encode(random_bytes(16));
    $GLOBALS['ms_csp_nonce'] = $nonce;

    $csp = "object-src 'none'; base-uri 'none'; "
         . "script-src 'nonce-$nonce' 'strict-dynamic' 'unsafe-inline' https: http:; "
         . "img-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https: data:; "
         . "connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.google.com;";

    header("Content-Security-Policy-Report-Only: $csp");
});

// Attaches the nonce to every script WordPress generates (including wp_enqueue_script)
add_filter('script_loader_tag', function ($tag, $handle) {
    if (!empty($GLOBALS['ms_csp_nonce']) && strpos($tag, 'nonce=') === false) {
        $tag = str_replace(' src=', ' nonce="' . esc_attr($GLOBALS['ms_csp_nonce']) . '" src=', $tag);
    }
    return $tag;
}, 10, 2);

This skeleton covers scripts registered through WordPress’s standard hooks. A theme or plugin that prints a hardcoded <script> tag inside a template will need the nonce attribute added manually, reading $GLOBALS['ms_csp_nonce'] — notably for the inline script that calls adsbygoogle.push() after the AdSense loader.

Plugins that inject their own inline scripts without going through wp_enqueue_script — some heatmap, chat or popup tools — slip past the script_loader_tag filter and silently break a strict CSP. A quick audit of the rendered page (right-click, “View page source”) helps spot any <script> tag missing a nonce attribute before switching to an enforced policy.

Testing without breaking monetization

Staying on Content-Security-Policy-Report-Only while validating the configuration is the only safe method before actually blocking anything: that header logs violations without stopping resources from loading. Google’s Tag Assistant extension shows, in its “Page issues” tab, exactly which resources a given CSP would block, making it possible to adjust the policy before switching to an enforced Content-Security-Policy header. Plan on roughly a week of real traffic to cover every path (pages with and without ads, forms, internal search) before flipping the policy live. For keeping an eye on the audience during that phase, the dashboard described in GA4 and Search Console for running a site is worth checking alongside it.

What to remember

A generic, fixed-domain CSP doesn’t survive long against the AdSense + GA4 combination: both services recommend a nonce-based policy built on 'strict-dynamic', which adapts to the scripts they load dynamically. WordPress doesn’t ship this mechanism out of the box, but a few lines in an mu-plugin are enough to set it up, provided it’s verified in Report-Only mode that no third-party plugin injects an inline script outside the standard pipeline.

This is one of the rare cases where I recommend keeping a CSP in Report-Only mode longer than usual on a site that lives off advertising: the cost of a false positive silently blocking ads for several days far outweighs that of a slightly less strict security policy during the testing phase. On projects where ads are the main revenue source, I even keep a looser fallback header as a safety net until the enforced policy has proven itself over several weeks. — Simon Janvier

Further reading: Google’s official CSP guide for Tag Manager and GA4, and AdSense’s CSP documentation.

Read next