SiteTidy
HomeGuidesConfiguring Content Security Policy (Part 5): Third-Party Scripts Without Destroying Your CSP
Security

Configuring Content Security Policy (Part 5): Third-Party Scripts Without Destroying Your CSP

Handle analytics, tag managers, payment widgets, chat and consent scripts under CSP. Learn nonce propagation, strict-dynamic, iframe isolation, vendor allowlists and when not to trust third-party JavaScript at all.

Published on August 15, 2026Updated August 31, 2026
Configuring Content Security Policy (Part 5): Third-Party Scripts Without Destroying Your CSP

The fastest way to turn a clean Content Security Policy into a sprawling mess is to add third-party JavaScript.

Your application starts with one bundle from your own origin. Then marketing wants analytics. Support wants chat. Finance wants a payment widget. Compliance adds a consent platform. Product adds A/B testing. Somebody drops in a tag manager that can inject more tags later.

Six months later, script-src contains a graveyard of domains nobody is willing to remove because nobody is entirely sure what they do.

This guide is about avoiding that outcome.

Third-party JavaScript is not inherently bad, but every script you intentionally allow to execute in your page becomes part of your browser trust boundary. CSP can control how that trust is granted. It cannot make an untrustworthy vendor script safe simply because you wrote the policy carefully.

The uncomfortable truth: an allowed script runs as your site

Suppose you include:

<script src="https://vendor.example/widget.js"></script>

Once the browser allows that script to execute, it can generally interact with your page like your own JavaScript can.

Depending on the page, that may include:

  • reading DOM content;
  • attaching event listeners;
  • modifying forms;
  • making same-origin requests with ambient browser credentials;
  • reading non-HttpOnly storage;
  • injecting more UI;
  • loading additional scripts;
  • observing user interactions.

CSP decides whether the script is allowed to execute.

It does not sandbox the script merely because it came from another domain.

That distinction should shape every third-party integration decision.

First question: does this need to be JavaScript?

Before adding a new source to CSP, ask whether the feature can be delivered another way.

Examples:

Social share button     -> ordinary link instead of JS widget
YouTube/video           -> iframe instead of site-wide script
Analytics event         -> server-side event where appropriate
Font                    -> self-host instead of JS loader
Support link            -> normal URL instead of chat SDK
Consent text            -> first-party UI instead of third-party DOM injection

This is not about eliminating all third-party code.

It is about refusing to give JavaScript execution privilege to functionality that does not need it.

Second question: can the vendor be isolated in an iframe?

Some third-party functionality naturally belongs in a frame:

  • payment elements;
  • video players;
  • identity/authentication widgets;
  • document viewers;
  • rich embeds.

If the vendor can operate inside a cross-origin iframe, your top-level page does not have to execute all of its JavaScript directly.

You might permit:

frame-src https://payments.example.com

instead of adding the vendor to script-src.

Cross-origin iframe isolation is not absolute — postMessage, navigation, permissions and embedding behaviour still need careful design — but it is a much clearer security boundary than giving third-party code direct execution in your document.

Host allowlists do not become safe just because the hostname is famous

This policy:

script-src 'self' https://cdn.bigvendor.example

trusts any script that can be loaded from that allowed source according to CSP matching rules.

Large vendors often host many products, user-controlled assets, legacy endpoints and dynamically generated resources.

A famous domain is not automatically a narrow trust boundary.

This is one reason strict nonce/hash CSP is preferred over giant host allowlists.

The better strict-CSP pattern: trust the bootstrap intentionally

For a server-rendered application using per-response nonces:

Content-Security-Policy:
  script-src 'nonce-{NONCE}' 'strict-dynamic';
  object-src 'none';
  base-uri 'none'

then intentionally nonce the vendor bootstrap:

<script
  nonce="{NONCE}"
  src="https://vendor.example/loader.js">
</script>

You have made a much more explicit decision:

this particular script element is trusted on this response.

You are no longer trusting the vendor’s entire hostname merely because it appears in script-src.

Where strict-dynamic helps

Many vendor loaders do not stop at one script.

They do something like:

Trusted vendor loader
      │
      ├── load analytics runtime
      ├── load region-specific bundle
      ├── load consent integration
      └── load additional tag

Maintaining every downstream hostname can become painful and fragile.

With a nonce/hash-authorised root plus 'strict-dynamic', trust can propagate to scripts loaded programmatically by that trusted root.

That is exactly the class of problem strict-dynamic was designed to help with.

But it changes the risk model.

You are now trusting the bootstrap not only to execute, but to make safe decisions about what it loads.

If it builds script URLs from attacker-controlled input, CSP may not save you.

Tag managers are a special category of trust

A tag manager is effectively a script whose job is to decide what other scripts to execute.

That makes it operationally convenient and security-sensitive.

Google’s current Tag Manager CSP guidance supports nonce-based deployment and recommends using CSP violation reporting while configuring the integration.

A typical nonce-aware pattern passes the page nonce into the GTM bootstrap so dynamically created scripts can inherit the trusted execution path.

The important conceptual point is bigger than the exact snippet:

Your CSP trusts GTM bootstrap
          │
          ▼
GTM configuration decides future scripts

So your tag-manager account permissions and publishing workflow become part of your application security model.

If somebody can publish arbitrary Custom HTML tags, they may effectively have production JavaScript execution capability.

Treat tag-manager administration accordingly:

  • MFA;
  • least-privilege access;
  • review/approval workflows;
  • audit history;
  • remove old users;
  • restrict Custom HTML/custom JavaScript where practical.

Do not solve tag-manager pain with 'unsafe-inline'

Tag-manager snippets historically pushed teams toward policies like:

script-src 'self' 'unsafe-inline' https://www.googletagmanager.com

That may make the integration work, but allowing arbitrary inline script weakens one of CSP’s central XSS protections.

If the vendor documents a nonce-compatible or hash-compatible approach, use that instead.

The right question is not:

“What do I add until the console goes quiet?”

It is:

“What is the narrowest CSP mechanism this vendor officially supports?”

Analytics usually needs more than script-src

A common rollout mistake is allowing the analytics script but not its network traffic.

For example:

script-src ... analytics.example.com;
connect-src ... metrics.example.com

The script executes, but beacon/fetch requests may be controlled by connect-src.

Other integrations may also require:

  • img-src for tracking pixels;
  • frame-src for embedded UI;
  • style-src for injected styles;
  • font-src for vendor fonts;
  • worker-src for background processing.

Read the vendor’s current CSP documentation rather than guessing from the initial <script src>.

Payment providers: prefer their intended isolation model

Payment providers often deliberately separate sensitive card-entry UI into provider-hosted frames.

That is good architecture.

A payment integration may require a mix of:

script-src   -> provider SDK/bootstrap
frame-src    -> secure card/payment frames
connect-src  -> provider APIs/telemetry
img-src      -> assets

Do not replace the provider’s recommended integration with a homemade broad allowlist.

Also test real payment flows under enforcement:

  • initial card entry;
  • 3-D Secure/challenge flows;
  • saved payment methods;
  • wallet buttons;
  • failure paths;
  • region-specific redirects.

The happy-path page load is not enough.

Chat widgets are often much larger than they look

A single chat snippet may trigger:

script CDN
WebSocket connection
REST API
avatar image CDN
font CDN
iframe
storage
notification assets

That can spread across several CSP directives.

Before permanently granting every source, decide whether chat genuinely needs to be present on sensitive routes such as:

  • checkout;
  • password reset;
  • account security;
  • admin panels.

Sometimes the safest policy is route-level product design:

the third-party widget does not run on the sensitive page.

A consent-management platform often needs to control whether other tags run.

That means the consent script itself may become one of the earliest trusted scripts on the page.

If it is compromised or misconfigured, it can affect the very scripts it is supposed to govern.

Keep the consent integration as narrow as possible and understand:

  • what code executes before consent;
  • what the platform dynamically inserts;
  • whether it uses inline script/style;
  • which network destinations are contacted before and after consent;
  • how CSP nonce propagation works;
  • whether configuration changes can introduce arbitrary code.

CSP and privacy controls overlap operationally even though they solve different problems.

A/B testing and personalisation are CSP-hostile by nature

Client-side experimentation tools often work by:

  • running very early;
  • altering DOM content;
  • injecting styles;
  • executing configuration logic;
  • loading experiment code dynamically.

That tends to collide with strict CSP.

Before weakening the policy, consider whether experimentation can move server-side or into first-party application code.

If a tool requires 'unsafe-eval', broad inline script permission and several wildcard origins, the security cost should be part of the vendor decision — not discovered months later during CSP deployment.

Subresource Integrity can help with stable third-party assets

If a third-party script is versioned and immutable, SRI can verify the fetched bytes:

<script
  src="https://cdn.example/library-4.2.1.min.js"
  integrity="sha384-..."
  crossorigin="anonymous">
</script>

If the CDN later serves different bytes at that URL, the browser refuses to execute them.

This is useful for static libraries.

It is usually not compatible with vendor endpoints that intentionally change content at the same URL, such as live analytics/tag-manager loaders.

SRI is strongest when the resource is meant to be immutable.

Self-hosting third-party code: useful, but not a free win

You may think:

“I’ll download the vendor script and serve it from my own domain. Then CSP can just use 'self'.”

That can improve control, caching and supply-chain pinning for some libraries.

It can also create new responsibilities:

  • security updates become your job;
  • vendor licence/terms may prohibit it;
  • scripts may rely on their original origin;
  • the library may load additional remote resources anyway;
  • you may freeze a vulnerable version;
  • 'self' host trust is still broader than nonce/hash trust.

Self-host because it fits the dependency model, not merely to make the CSP shorter.

Do not use * because a vendor has “lots of domains”

This:

script-src *

is not a CSP strategy.

Neither is:

connect-src *

unless your application’s explicit design genuinely requires arbitrary destinations and you understand the consequences.

If a vendor cannot document the network origins its production integration needs, that is useful security information about the vendor.

Wildcard subdomains deserve scrutiny too

This:

script-src https://*.vendor.example

trusts every matching subdomain.

Ask:

  • are any subdomains customer-controlled?
  • can users upload files there?
  • are there abandoned DNS records?
  • does the wildcard include old products?
  • is the vendor’s own CSP guide asking for the wildcard, or did somebody guess it?

A precise origin list or nonce-authorised root may be safer.

Third-party CSP documentation goes stale

Vendor integration guides change.

A payment provider adds a new challenge domain. Analytics moves collection endpoints. A consent platform replaces one CDN with another.

This means third-party CSP is not “configure once and forget”.

For each critical vendor, record:

Vendor
Purpose
Owner inside your company
Official CSP documentation URL
Required directives/origins
Date reviewed
Routes where loaded
Removal process

That turns a random header entry into an owned dependency.

Third-party scripts leave fingerprints on the public site

A SiteTidy audit can help you inspect the final public page and header posture after vendor integrations change — useful alongside CSP reports and your browser tests.

Run Free Audit →

A vendor review before adding CSP permissions

Before adding a new third-party script, answer these questions:

What privilege are we granting?

Does it execute directly in the top-level page, or can it be isolated in a frame?

Is the script static or mutable?

Can we pin it with SRI/hash, or does the vendor intentionally change the resource behind a stable URL?

What does it load next?

Does it create further script tags, workers, frames or styles?

What network destinations does it need?

Document connect-src, frame and asset requirements.

Which pages need it?

Do not run site-wide JavaScript if only one route uses the feature.

Who owns the vendor account/configuration?

A tag-manager or experimentation account with arbitrary-code capability deserves production-grade access controls.

What happens if the vendor is unavailable?

Does checkout stop? Does the page fail closed? Can the script block rendering?

How do we remove it?

Dependencies with no owner rarely disappear cleanly.

Use route-specific loading to reduce blast radius

Imagine your site has:

Marketing pages
Dashboard
Checkout
Admin

Maybe analytics is justified on marketing pages and dashboard.

Maybe payment scripts only belong on checkout.

Maybe neither belongs in admin.

If your application architecture allows it, only render the script on routes that need it.

This improves:

  • security;
  • performance;
  • privacy;
  • CSP simplicity;
  • troubleshooting.

The safest third-party script on a sensitive route is often the one that never loads there.

Third-party scripts and connect-src

Even with strict script trust, data exfiltration controls deserve separate attention.

If an attacker somehow gains script execution, a restrictive connect-src may limit direct fetch()/XHR/WebSocket/beacon destinations.

For example:

connect-src 'self' https://api.example.com https://metrics.example.com

This is useful defence in depth.

But do not overstate it: data can potentially leave through other permitted resource mechanisms depending on the policy and browser behaviour.

A strict, well-designed policy reduces multiple avenues rather than relying on one directive as a perfect exfiltration firewall.

strict-dynamic vs host allowlists: know which model you are using

This policy:

script-src 'nonce-ABC' 'strict-dynamic' https://vendor.example

can mislead reviewers into thinking the vendor hostname is the key permission.

In modern CSP3 browsers, with a valid nonce/hash and strict-dynamic, host source expressions are ignored for script loading under that directive.

The trusted root and trust propagation are what matter.

Document that so a future engineer does not remove the nonce and accidentally turn the policy back into a host allowlist.

What to do when the vendor says “add unsafe-inline and unsafe-eval”

Do not immediately comply.

Ask:

  1. Is that guidance current?
  2. Does the vendor support a nonce?
  3. Is there a CSP-specific build/integration?
  4. Is unsafe-eval development-only?
  5. Can the feature be embedded in an iframe?
  6. Can we choose a different vendor?
  7. Is the business value worth weakening CSP globally?

Sometimes you will consciously accept a weaker policy because the integration is essential and there is no practical alternative.

That should be an explicit risk decision, not a console-error fix.

Test the vendor’s weird flows

Third-party integrations frequently behave differently during edge cases.

Examples:

Payment success       -> normal provider endpoints
Payment challenge     -> additional frame origin
Payment failure       -> error telemetry endpoint
Chat open             -> WebSocket established
Chat file upload      -> storage CDN
Consent rejection     -> different tag sequence
A/B test assignment   -> dynamic script or config request

Exercise those flows while report-only/enforcement is active.

Production CSP failures often live in the branch nobody tested.

A practical third-party policy inventory

Use something like:

Vendor: ExamplePay
Owner: Payments team
Routes: /checkout, /billing
script: https://js.examplepay.com (nonce-authorised root)
frame:  https://secure.examplepay.com
connect:https://api.examplepay.com
img:    https://assets.examplepay.com
SRI:    not possible; loader is mutable
Reviewed: 2026-08-31

Now six months later you can answer why those permissions exist.

Compare that with a CSP containing:

*.examplepay.com

and no explanation.

The “remove it” test

Temporarily disable a third-party integration in staging. If nobody knows what breaks, you have discovered an unowned production dependency. Fix the ownership problem before giving it broader CSP permissions.

Browse SiteTidy's security tools

Final thought

Third-party JavaScript is where CSP becomes a business architecture discussion rather than a header exercise.

Every vendor script represents a deliberate transfer of trust.

A strong approach asks, in order:

Do we need it?
Can we isolate it?
Can we authorise a narrow bootstrap with nonce/hash?
Can strict-dynamic handle its loader model safely?
Can static assets use SRI?
Which routes actually need it?
Who owns the vendor configuration?
What CSP permissions does it truly require?

If you start there, your policy remains understandable.

If you start by copying every hostname from every vendor help article into script-src, CSP gradually turns back into a giant allowlist — exactly the model strict CSP was meant to move beyond.

In Part 6, we will look at frameworks and build systems: React, Vue, Angular, Next.js, Nuxt, Astro and the practical reasons development builds, hydration, inline styles, code splitting, WebAssembly and bundlers can collide with an otherwise clean CSP.

Ready to audit your site?

Put this guide into practice immediately using our free tools.

Browse 180+ Free Tools