22/2/2026
How to Configure a Content Security Policy (CSP) for Google Tag Manager Without Breaking Tracking or Web Security
If you are already managing consent, cookies and tag firing order, keep that framework in mind before tightening script loading security: our guide to Google Tag Manager cookies covers compliance and tagging governance in depth. Here, we focus on a more technical matter: configuring a Content Security Policy (CSP) for Google Tag Manager to prevent "blocked" errors while strengthening protection against script injection.
What This Article Covers (and What Stays in the Consent and Cookies Guide)
This article focuses strictly on browser security: why a CSP can block Google Tag Manager, which directives are involved (especially script-src, connect-src and img-src), and how to choose between three practical strategies: allowlisted domains, a nonce, or a hash.
Everything related to ePrivacy/GDPR compliance, consent-gated tag firing, and prior-consent logic remains in the dedicated consent and cookies article, to avoid repetition and cannibalisation.
Why a CSP Can Show "Blocked": What It Prevents and How It Strengthens XSS Protection
A Content Security Policy forces the browser to execute and load only explicitly authorised resources. By default, it blocks behaviours commonly exploited in XSS attacks: inline JavaScript injection, loading scripts from unapproved domains, or running dynamic evaluation mechanisms.
The catch is that Google Tag Manager relies on a loader script (gtm.js) and then dynamically injects additional scripts and tags. With a strict policy in place, the browser may refuse to load the GTM script — for example, displaying "Refused to load the script because it violates the Content Security Policy" — if the sources are not allowed or if the required inline snippet is not handled via a nonce or hash.
Understanding the Conflict Between CSP and GTM: Mechanisms, Risks and Attack Surface
Definition: Content Security Policy (CSP), Goals, Limitations and the Browser's Role
A CSP is a browser-enforced security layer, typically defined via the Content-Security-Policy HTTP response header (or, less commonly, a <meta http-equiv='Content-Security-Policy'> tag). It restricts which origins are permitted for scripts, images, styles, network connections, iframes, and more. In practice, it reduces the XSS attack surface, but it does not fix vulnerabilities: it limits the impact of a successful injection.
Technical Reminder: How Google Tag Manager Loads (Snippet, iFrame, Injections) and Why That Triggers Violations
A GTM implementation starts with a snippet (often inline) that initialises the dataLayer and loads gtm.js from a Google domain. Once loaded, GTM can:
- inject additional scripts (marketing, analytics, conversion) based on the published tags;
- trigger network requests to measurement endpoints;
- load pixels (images) or use iframes (including for some Google products and for preview and debug contexts).
It is this combination of inline code, remote loading and dynamic injection that causes CSP violations unless you explicitly include the required directives.
Map What Your Container Actually Calls: Scripts, Network Endpoints, Images and Pixels to Allow
Before writing a strict policy, list what is genuinely used:
- Scripts: the GTM loader (for example,
www.googletagmanager.com), then the domains for each triggered tag. - Network connections: collection endpoints (for example,
*.googletagmanager.comand, depending on your setup, Google Analytics endpoints). - Images: pixels and beacons (for example, GTM or GA subdomains, or other vendors).
Key point: allowing GTM alone is not sufficient if your container then loads third-party tags. A strict CSP requires ongoing governance — every new tag may require an update to the policy.
Preparing Before You Tighten CSP: Deployment Settings and a Safe Iteration Loop
Choose Between Content-Security-Policy and Report-Only to Iterate Safely
To avoid breaking tracking in production, start with Content-Security-Policy-Report-Only: the browser reports violations but does not block anything. Once the directives are stable, switch to Content-Security-Policy enforcement.
Read Violation Reports and Logs to Identify the Failing Directive
Diagnostics typically come from:
- your browser console (messages such as "Refused to load…" with the relevant directive named);
- CSP reports (if you have configured a reporting endpoint), which are useful for aggregating issues across real traffic.
In practice, the error line nearly always names the responsible directive: script-src, connect-src, img-src, and sometimes frame-src.
Pre-Production Checklist: Environments, Cache/CDN, Preview Mode and Debug Impact
- Validate on a staging environment that mirrors the CDN or reverse proxy and the final response headers.
- Test Preview mode: common symptoms include a broken debug panel, missing styles, and CSP errors in the console.
- Check critical user journeys (landing page, form, checkout): these are often where measurement is most sensitive.
Minimum CSP Rules for Tag Manager to Work: Directives and Trade-Offs
script-src: Allow the Loader, Control Inline Script Policy and Avoid Unnecessary Openings
For GTM, script-src is the most critical directive: it must cover the loader and your chosen strategy for inline scripts (nonce or hash). A minimal starting point can look like this:
Content-Security-Policy: script-src 'nonce-{nonce}';
You will then need to add the domains that are actually required (preview, triggered tags, and so on). Simply adding a domain is often not enough if the inline snippet is not properly authorised.
When Allowing GTM Requires a Nonce: Handling Inline Scripts Properly
The most robust approach for GTM under a strict CSP is to use a nonce (a random value generated per HTTP response) combined with 'strict-dynamic'. This is a natural fit for systems that load scripts dynamically — a typical GTM pattern — because it avoids maintaining a long list of hashes and instead trusts scripts loaded by an already-approved script.
Example (adapt as needed):
Content-Security-Policy: script-src 'nonce-{nonce}' 'strict-dynamic';
In practice, nonce combined with 'strict-dynamic' is often the best compromise between functionality and a reduced XSS surface area, precisely because GTM loads resources dynamically.
unsafe-inline and unsafe-eval: Why They Weaken Security and How to Avoid Them
Two tokens frequently appear when GTM stops working: 'unsafe-inline' and 'unsafe-eval'. They can unblock situations quickly — especially during preview or debug — but they significantly relax the policy.
'unsafe-inline'permits inline JavaScript execution, which is precisely what a CSP aims to restrict in order to reduce injection impact.'unsafe-eval'permits evaluating strings as JavaScript (for example,eval()andnew Function). This tends to become necessary mainly when you rely on Custom HTML tags and Custom JavaScript variables in GTM. Without those elements, you may be able to avoid it entirely.
The recommended goal is to treat these as a last resort and to favour nonce or hash combined with a refactor of custom tags wherever possible.
connect-src: Allow the Required Network Calls Without Over-Allowlisting
connect-src governs JavaScript network requests (fetch, XHR and beacons). For GTM, a common baseline is allowing the necessary subdomains:
Content-Security-Policy: connect-src https://*.googletagmanager.com;
If you also measure via Google Analytics, you may need to add dedicated endpoints (for example, *.google-analytics.com and *.analytics.google.com), but avoid broadening the policy without first verifying the actual calls observed in Report-Only mode.
img-src: Pixels, Beacons and the data: Pitfall
img-src covers tracking pixels and beacons (often implemented as image requests). A typical configuration should allow only the domains you genuinely use, for example:
Content-Security-Policy: img-src https://*.googletagmanager.com;
Be cautious with the data: scheme: it may be required by certain implementations, but it also widens the attack surface. Decide based on real violations and genuine needs.
Three Ways to Allow GTM With a Strict CSP: Domains, Nonce and Hash
Approach 1: Start Quickly With an Allowlist of Domains
The simplest strategy is to explicitly allow GTM domains in script-src. A minimal example commonly used to unblock loading is:
Content-Security-Policy: script-src 'self' https://www.googletagmanager.com;
Limitation: in practice, this may not be sufficient, and you may also need to include subdomains (https://*.googletagmanager.com) depending on what is called. This approach is quick to implement, but it becomes brittle when your container changes frequently or new tags are introduced.
Approach 2: A Server-Side Nonce for a Strict Policy With Dynamic Loading
For a strict CSP that remains compatible with GTM's dynamic injection patterns, a nonce is generally the most sustainable option. The principle is straightforward: generate a unique nonce per response, declare it in script-src, and apply it to the permitted inline scripts (including the GTM initialisation snippet).
Generate, Inject and Propagate the Nonce: Snippet, Templates and Critical Pages
A typical implementation involves three steps:
- generate a nonce server-side (one per page load);
- insert it in the CSP header (
script-src 'nonce-…'); - add a matching
nonce='…'attribute to the inline GTM snippet.
Whatever your framework, the non-negotiable rule remains the same: the nonce must be produced server-side and used identically in both the header and the inline <script> element.
Custom HTML Tags: Pass Through the Nonce and Avoid Security Workarounds
If you use Custom HTML tags, they can introduce additional inline code and push you towards 'unsafe-inline' or 'unsafe-eval'. A safer strategy is to pass the nonce (for example, via an application-exposed variable) and only permit nonced scripts, rather than opening the policy globally.
Crucially, avoid workarounds that make GTM function by weakening security, as they reintroduce precisely the risk that a CSP is designed to reduce.
Approach 3: A Hash for a Fixed Inline Snippet (and When It Breaks)
Hash-based policies allow one precise inline payload via sha256-… (or sha384 or sha512) inside script-src. The advantage is that you do not need a runtime nonce. The main drawback is maintenance: as soon as the inline snippet changes — even by a single space — the hash becomes invalid and must be recalculated and redeployed.
CSP Header Examples: Keeping "Allow googletagmanager" Tight Without Over-Permissioning
Structure the Header: Base Policy, Necessary Exceptions, Then Progressive Hardening
A readable structure helps prevent syntax errors (directives must be separated by semicolons) and keeps the policy under control. Example (adapt to your actual needs):
Content-Security-Policy: default-src 'self'; script-src 'nonce-{nonce}' 'strict-dynamic'; connect-src https://*.googletagmanager.com https://*.google-analytics.com https://*.analytics.google.com; img-src https://*.googletagmanager.com https://*.google-analytics.com; frame-src https://*.google.com; style-src 'self' 'unsafe-inline';
Note: the style-src example above includes 'unsafe-inline' because certain debug panels and interfaces depend on it. This is not universally required. Where your architecture permits, restrict such relaxations to debug environments or specific pages.
Deploy for Your Stack: Web Server, Reverse Proxy, CDN or Application (Avoid Duplication)
Deploy your CSP from a single "source of truth" — whether that is a reverse proxy, CDN or the application itself — to avoid divergence (duplicate headers, inconsistent rules, and harder debugging). If you vary the policy per environment, document and version those differences.
Verify the Header Is Active: Browser, curl and Conversion Flows
- In the browser: open the Network tab and check the
Content-Security-Policyresponse header. - On the command line:
curl -I https://your-domain.tld/page. - In QA: test the conversion journeys where your most sensitive tags fire.
Fixing a CSP-Related "Blocked" Error Quickly: A Diagnostic Method
Read the Console Error and Identify the Blocking Directive (script-src, connect-src, img-src)
Start with the console: the error identifies the directive and often the blocked resource URL. A common example is a script refused because it violates script-src. Use that as your evidence-based starting point rather than guesswork.
Common Cases: Preview Mode, Third-Party Tags, Custom HTML, Redirects and iFrames
- Preview: the debug panel may not appear, or may lose its styling, if
style-srcis too strict. - Third-party tags: a recently added pixel not covered by
img-srcorconnect-src. - Custom HTML: can introduce requirements for
'unsafe-eval'(Custom JavaScript variables) or additional inline allowances. - iFrame: may require adjusting
frame-srcif a Google flow depends on it.
When Consent Mode Changes Script Loading Behaviour
In consent-driven setups, some tags fire only after a user opts in. As a result, certain CSP violations may only appear in an "accept" scenario. Test multiple scenarios — reject, partial accept, and full accept — to cover all resources that may actually load.
Hardening Beyond CSP: GTM Governance, Trusted Types and Injection Prevention
Why Tag Manager Increases Risk When Governance Is Weak (Permissions, Workflows, Validation)
GTM centralises the ability to inject code. Without proper governance — permissions, review processes, staging environments and versioning — you increase the likelihood of adding a tag that forces an emergency CSP exception or introduces patterns incompatible with a strict policy. CSP then becomes a useful diagnostic signal: if every marketing change requires 'unsafe-inline', the problem is as much organisational as it is technical.
Trusted Types: Reduce Risky DOM Sinks and Complement CSP in Modern Applications
Trusted Types can complement a CSP strategy by reducing exposure to DOM XSS on certain sinks (for example, innerHTML). In modern, highly dynamic applications, it adds a useful additional barrier alongside script-src. The aim is not to replace CSP, but to further narrow the pathways available for injection.
Ongoing Maintenance: Versioning, Tag Reviews and Post-Release Testing
A strict CSP demands discipline: regular tag reviews, documentation of external resources, and systematic testing after every container release. Keep CSP reporting enabled continuously — it acts as a safety net for detecting unexpected calls early.
GEO Angle: Impact on Visibility in Generative AI Answers
What CSP Can Affect Indirectly: Performance, Rendering, Measured Signals and Data Quality
A poorly calibrated CSP can break critical resources (rendering scripts, pixels, endpoints), degrade the user experience (JavaScript errors, broken features), or distort data collection. Indirectly, this can undermine your SEO and GEO decisions if performance data becomes incomplete or inconsistent.
Conversely, an overly permissive CSP widens the attack surface and may erode trust. Trust and security influence overall performance — conversion rates, engagement — which in turn shapes content prioritisation decisions.
Link Measurement and Steering: Use Google Analytics and Google Search Console in Incremys via API
To avoid misreading the impact of header changes, it helps to bring visibility (Search Console) and behaviour (Analytics) together. Incremys integrates and encompasses Google Search Console and Google Analytics via API within a 360° SEO approach, making it easier to identify whether tightening a CSP has introduced a break — drops in measured conversions, attribution gaps, or template-level anomalies.
When CSP Exposes a Wider Issue: What to Audit on the Technical Side
Typical Symptoms: Duplicate Scripts, Unexpected Resources, Uncontrolled Dependencies
- Two competing GTM implementations (a hard-coded snippet alongside one loaded via a module);
- tags added without documentation, calling unknown domains;
- dependencies loaded differently across pages due to inconsistent templates;
- environment discrepancies between staging and production caused by the CDN or reverse proxy.
A Structured Approach: a Technical SEO Audit (Performance, Security and Measurement Reliability)
When CSP violations multiply, the root cause is often not a "GTM problem" but a symptom of technical debt and poor script governance. A technical SEO audit can help you reset the chain: performance, security, template consistency and measurement reliability — without resorting to an ever-growing list of CSP exceptions.
Benchmarks and Decision-Making: Balancing Measurement, Security and Reliability
Prioritise With SEO Data: Pages, Templates and Risk Levels
Begin with the pages that matter most for revenue and organic traffic, then harden template by template rather than attempting a big-bang release. To frame that prioritisation, you can draw on benchmarks and trends consolidated in our SEO statistics — covering CTR, click distribution, mobile performance and engagement signals — to identify where a tracking or rendering break would prove most costly.
Add SEA Data If CSP Impacts Paid Tracking
If your container fires advertising tags, an overly restrictive CSP can break conversions, pixels or measurement endpoints. Document the campaign impact using benchmarks from our SEA statistics and your own conversion checks after deployment.
Track GEO Changes to Frame the Generative Landscape
As generative AI answers become more prominent, signal quality — content, performance, measured data — increasingly informs strategic decisions. To contextualise these shifts, you can compare your observations with our GEO statistics and connect those trends to your CSP hardening decisions, ensuring you do not inadvertently harm rendering or measurement in the process.
A Note on Incremys
Document Governance, Connect Data and Prioritise ROI-Driven Fixes
A CSP that works with GTM is not simply a header: it is a decision-making system covering which tags to allow, which domains to permit, what level of inline script to accept, and what validation process to enforce. Incremys helps connect visibility, content and performance through a data-driven approach, enabling you to prioritise technical fixes — including those that affect measurement — based on measurable impact rather than intuition.
FAQ: CSP and Google Tag Manager
Is GTM Compatible With a Strict Content Security Policy?
Yes, but rarely through a simple allowlist alone. A strict CSP is typically more compatible with GTM when you handle inline scripts properly (via a nonce or hash) and allow the actual network calls (connect-src) and pixels (img-src) in use. A nonce combined with 'strict-dynamic' is often the most robust approach for managing dynamic loading.
How Does Google Tag Manager Work, and Why Does That Complicate a Strict CSP?
GTM loads an initial script (for example, gtm.js), then dynamically injects other scripts and tags and triggers requests to measurement endpoints. A strict CSP blocks that behaviour unless it is explicitly authorised.
Where Can I Find the Container Code in Google Tag Manager?
In the GTM interface, open the container and navigate to the installation section (typically via Admin and the install option). You can then copy the snippet for placement in the <head> (and the <noscript> variant if you use it).
What Should I Configure in GTM Before Changing the CSP Header?
Stabilise your container first: active tags, Custom HTML tags, Custom JavaScript variables, and your preview and debug scenario. Then run an observation phase using Content-Security-Policy-Report-Only to see what GTM and your tags actually call.
Which CSP Directives Should I Adjust First (script-src, connect-src, img-src)?
Start with script-src (loading and inline handling), then connect-src (network endpoints), and finally img-src (pixels). Add frame-src if specific flows require it.
How Can an Allowlist Approach Enable GTM Without Opening Things Too Wide?
Allow only the domains you genuinely need (for example, https://www.googletagmanager.com and sometimes https://*.googletagmanager.com), then validate via Report-Only and console output. The downside is maintainability: this approach becomes difficult to manage when your container frequently adds or changes tags and endpoints.
Should I Use Allowlisted Domains, a Nonce or a Hash?
For sites that evolve quickly — with tags added or changed regularly — a nonce is often the most sustainable choice. A hash works best when your inline snippet remains perfectly unchanged. A simple allowlist can help you get started, but it becomes fragile as soon as GTM dynamically loads additional scripts.
What Errors Occur If Allowing Google Tag Manager Remains Incomplete?
You will see console errors such as "Refused to load the script…" (blocked by script-src), blocked network requests (incomplete connect-src), or refused pixels (incomplete img-src). In some cases, allowing www.googletagmanager.com without its subdomains leaves residual blocks in place.
What Should I Do If Preview Mode Stops Working After Hardening and Shows "Blocked"?
Test in Report-Only mode first to capture the violations specific to preview. Then review script-src (required domains and inline handling), style-src (the panel can lose its styling if too strict), and any domains involved in the preview interface.
Which Nonce Should I Use With GTM, and Where Do I Inject It?
Use a server-generated nonce that is unique per page load. Inject it in two places: in the response header (script-src 'nonce-…') and in the nonce='…' attribute on the inline <script> that initialises GTM. The value must match exactly in both locations.
Which Hash Should I Choose for the Inline Snippet, and When Does This Approach Become Fragile?
Compute a sha256, sha384 or sha512 hash from the exact content of the inline snippet and add it to script-src. This approach becomes fragile as soon as the snippet changes — even slightly — because the hash must be recomputed and redeployed.
How Can I Avoid unsafe-inline and unsafe-eval While Keeping Tags Functional?
Prefer a nonce (and potentially 'strict-dynamic') for inline scripts, and reduce reliance on Custom HTML tags and Custom JavaScript variables, which can push you towards 'unsafe-eval'. Where possible, replace arbitrary inline code with more structured implementations.
Where Should I Check That the CSP Header Is Being Sent, and Which Pages Should I Validate?
Check the header in your browser's Network tab or via curl -I. Prioritise high-stakes pages: SEO landing pages, forms, conversion funnels, and pages where marketing tags fire.
How Do I Deal With "Refused to Load…" Errors Related to connect-src and Measurement Endpoints?
Identify the blocked URL in the console, then allow the minimal required origin in connect-src. Do this in Report-Only mode first, and avoid over-allowlisting (for example, using *): every addition should correspond to a real, observed need.
Is CSP Enough for XSS Protection, or Should I Enable Trusted Types as Well?
CSP significantly reduces risk, but it does not replace fixing application-level vulnerabilities. Trusted Types can complement CSP in modern applications by reducing risky DOM sinks. Together — a strict CSP, Trusted Types and sound application security hygiene — they form a more coherent and layered defence.
How Do I Stop a Custom HTML Tag From Bypassing My Security Strategy?
Tighten publishing permissions, enforce review processes, document all tags, and limit the use of Custom HTML. On the CSP side, avoid global relaxations such as 'unsafe-inline'; prefer a nonce strategy and change-control processes that prevent arbitrary code from being introduced without validation.
GEO Angle: Can CSP Affect Visibility in Generative AI Answers via Performance and Data Quality?
Indirectly, yes: if a CSP breaks rendering or data collection, you degrade the quality of the signals — performance, engagement, conversions — that inform SEO and GEO prioritisation. A well-calibrated CSP improves security without disrupting operations, which in turn stabilises both your data and your decision-making.
What Checks Should I Run After Every Tag Release to Avoid Tracking Breaks?
Test key user journeys, review the console for CSP violations, check network requests (endpoints) and pixels, and compare volumes in Analytics and Search Console before and after the release. Maintain a history of GTM versions alongside the corresponding CSP changes.
To explore more topics across SEO, GEO and digital marketing, visit the Incremys Blog.
.png)
.jpeg)

%2520-%2520blue.jpeg)
.jpeg)
%20-%20blue.jpeg)
.jpg)
.jpg)
.avif)