Configuring Content Security Policy (Part 9): Debug CSP Errors Without Guessing
A hands-on CSP troubleshooting guide for nonce mismatches, inline script errors, strict-dynamic surprises, blocked APIs, workers, frames, duplicate policies, CDN conflicts and production-only failures.

Content Security Policy errors have a reputation for being cryptic.
They are much easier once you stop treating the entire header as one problem.
A CSP failure nearly always has four useful pieces of information hiding in front of you:
What did the browser try to do?
Which effective directive controlled it?
Which policy did the browser receive?
Was the attempted behaviour actually intended?
Answer those in that order and most CSP debugging becomes ordinary engineering rather than trial-and-error header editing.
This guide is the practical troubleshooting playbook: browser console messages, nonce failures, blocked network requests, strict-dynamic, duplicated headers, proxies, stale caches and the failures that appear only after a production deployment.
Rule zero: do not fix CSP by adding whatever the browser blocked
Suppose the console says:
Refused to load the script 'https://random.example/script.js'
because it violates the following Content Security Policy directive...
The worst debugging process is:
blocked origin
↓
copy origin
↓
append to script-src
↓
refresh
↓
repeat until errors stop
That turns CSP into a log-driven allowlist with no security model.
Instead ask:
- What feature requested this script?
- Should that feature exist?
- Who initiated the load?
- If it is legitimate, should it be trusted through a nonce/hash rather than hostname?
- Is the request coming from your application or a browser extension?
A CSP violation is evidence. It is not automatically a permission request.
Start with the browser’s effective directive
Modern browser errors usually identify the directive that actually blocked the action.
Examples:
script-src-elem
script-src-attr
style-src-elem
connect-src
img-src
font-src
frame-src
frame-ancestors
worker-src
form-action
require-trusted-types-for
That is your starting point.
If the error says connect-src, editing script-src will not help.
If it says frame-ancestors, adding the parent site to frame-src changes the wrong trust direction.
If it says script-src-attr, the problem may be an inline onclick handler rather than a missing external host.
Understand fallback messages
Sometimes the console says something like:
Note that 'worker-src' was not explicitly set,
so 'script-src' is used as a fallback.
That is extremely useful.
The browser is telling you that the resource class does not have its own directive, so another directive in the fallback chain controlled the decision.
Instead of broadening script-src to make a worker work, consider adding the more explicit directive:
worker-src 'self'
The resulting policy is easier to understand and usually narrower.
Problem: “Refused to execute inline script”
Typical causes:
- the script has no nonce;
- the nonce does not match the header;
- a hash is missing or wrong;
- an inline event handler is being treated as script;
- the page still relies on arbitrary inline code;
- you expected
'self'to cover inline JavaScript — it does not.
Given:
script-src 'nonce-ABC123'
this runs:
<script nonce="ABC123">
startApp();
</script>
this does not:
<script>
startApp();
</script>
and neither does this automatically:
<button onclick="startApp()">Start</button>
The fix depends on which kind of inline code you found.
Problem: nonce appears correct but the browser still blocks it
Check the actual response header and actual DOM, not the server-side source code.
Common causes include:
Header and HTML came from different cached responses
Response A:
CSP nonce: AAA
HTML nonce: AAA
Response B:
CSP nonce: BBB
HTML nonce: BBB
A badly configured cache can accidentally produce:
CSP nonce: BBB
HTML nonce: AAA
Every script is now blocked.
This is a classic nonce + CDN failure.
Proxy changed or duplicated the header
Your application emits one policy, while the reverse proxy appends another.
The browser enforces both.
Framework did not propagate the nonce to generated content
Your own <script> has the nonce, but the framework runtime or style injection does not.
Use the framework’s supported nonce mechanism rather than patching output blindly.
The nonce was HTML-escaped/transformed differently
Compare the bytes/value the browser receives rather than values in your debugger.
Inspect headers in DevTools Network, not only Elements
Open the document request in the Network tab and inspect Response Headers.
You want to know:
How many Content-Security-Policy headers arrived?
Is there a Report-Only policy too?
Did the CDN modify the value?
Is the nonce the expected one?
Is the policy on this exact route the same as the homepage?
The Elements panel tells you what the DOM looks like.
The Network panel tells you what security policy the browser was actually instructed to enforce.
Use both.
Problem: two CSP headers are present
This causes a lot of confusion.
Suppose your application sends:
Content-Security-Policy: connect-src 'self' https://api.example.com
and the CDN sends:
Content-Security-Policy: connect-src 'self'
The browser does not merge them into a union.
The request to https://api.example.com must satisfy both policies, and therefore it is blocked by the second one.
Multiple enforcing policies only make the result more restrictive.
Find every layer capable of setting headers:
application
web server
reverse proxy
load balancer
CDN
WAF
hosting platform
edge function
Then establish one ownership model.
Duplicate directives inside one policy are also a problem
MDN’s current CSP error reference notes that if the same directive appears multiple times in one policy, later duplicates may be ignored.
This is not safe:
Content-Security-Policy:
script-src 'self';
script-src https://cdn.example.com
Do not expect the browser to combine them into:
self + CDN
Build one intentional directive:
script-src 'self' https://cdn.example.com
Better still, for strong script protection, use the nonce/hash model appropriate to the application.
Problem: 'strict-dynamic' seems to make allowed hosts stop working
This is usually not a browser bug.
With a valid nonce/hash and 'strict-dynamic', modern CSP Level 3 browsers change the script trust model. Host/scheme expressions such as:
'self'
https:
https://cdn.example.com
are ignored for relevant script-loading decisions.
So:
script-src 'nonce-ABC' 'strict-dynamic' 'self' https://cdn.example.com
is primarily saying:
trust nonce-authorised root scripts
and scripts they legitimately load dynamically
not:
trust every script from self and CDN too
If a parser-inserted <script src="https://cdn.example.com/x.js"> lacks the nonce, it may be blocked.
Fix the trust root instead of removing strict-dynamic without understanding it.
Problem: dynamically created script is still blocked under strict-dynamic
Check how it is being created.
strict-dynamic trust propagation is designed around scripts loaded by trusted scripts through particular programmatic mechanisms.
A script appearing in parsed HTML is not automatically a trusted child merely because another trusted script exists on the page.
Verify:
- the parent/root script has a valid nonce/hash;
- the parent is the code actually creating the child;
- the framework/vendor loading mechanism matches CSP semantics;
- you did not render the child tag server-side without its own nonce.
The phrase “loaded after another script” is not the same as “loaded by a trusted script”.
Problem: stylesheet is blocked even though style-src 'self' exists
Check whether it is actually an external same-origin stylesheet.
These are different:
<link rel="stylesheet" href="/app.css">
and:
<style>
.button { color: red; }
</style>
The first is a same-origin resource.
The second is inline style content and requires the appropriate nonce/hash/inline policy.
Runtime CSS-in-JS libraries often create <style> elements dynamically. The source code may contain no visible inline CSS while the production DOM does.
Inspect the runtime DOM and framework docs.
Problem: inline style="..." attributes are blocked
A nonce on a <style> block does not automatically authorise every style attribute.
For example:
<div style="display:none"></div>
is a separate inline-style use case.
Options include:
- move styling into classes/external CSS;
- use framework-supported CSP styling mechanisms;
- use appropriate hash-based migration features where justified;
- as a last resort, consciously accept a broader style policy.
Do not weaken script policy because the issue is styling.
Problem: API calls fail after CSP enforcement
Look at connect-src.
Typical hidden endpoints include:
- REST API;
- GraphQL API;
- authentication token refresh;
- telemetry;
- feature flags;
- fraud detection;
- upload storage;
- analytics beacon;
- WebSocket;
- Server-Sent Events.
A frontend can load perfectly and still become non-functional because its data plane is blocked.
Use the Network tab alongside the CSP console violation to identify the real target.
Problem: WebSocket works locally but not in production
Development may connect to:
ws://localhost:5173
for hot-module replacement.
Production may need:
wss://realtime.example.com
Do not copy localhost permissions into production.
Also check that a deployment did not accidentally produce:
ws://realtime.example.com
from an HTTPS page, creating both mixed-content and CSP issues.
Problem: payment or authentication iframe is blank
Check frame-src first.
But do not stop at the first frame URL.
Authentication/payment flows may move through several origins:
initial provider frame
↓
challenge origin
↓
regional processor
↓
callback/confirmation
Reproduce the real workflow, including 3-D Secure, MFA and failure paths.
A test card that never triggers a challenge may not exercise the origin production customers need.
Problem: partner cannot embed your page
That is likely frame-ancestors, not frame-src.
If your policy says:
frame-ancestors 'none'
nobody can frame the page.
If it says:
frame-ancestors https://portal.example.com
only matching parents are authorised.
Check the actual parent origin including scheme and port.
Remember that frame-ancestors must be delivered via an HTTP header; a meta-delivered version is ignored.
Problem: worker or Service Worker registration fails
Start with worker-src.
For a conventional same-origin worker:
worker-src 'self'
For a generated blob worker:
worker-src 'self' blob:
Then verify whether the worker script response itself has a relevant CSP for its own execution/network environment.
For Service Workers, test stale/previous registrations too. A clean incognito session can quickly tell you whether the failure comes from current code or persistent old worker state.
Problem: Vite/webpack build works in dev but fails after build
Compare dev and production output.
Development may rely on:
- HMR WebSocket;
- dev-only eval;
- different inline scripts;
- injected client runtime;
- localhost resource origins.
Production may introduce:
- module preloads;
- code-split chunks;
- fingerprinted assets;
- inlined
data:assets; - extracted CSS.
CSP should be tested against both modes with different policies where appropriate.
A dev exception is not automatically a production requirement.
Debug the response users receive, not the header you intended
SiteTidy can inspect the public HTTP response after your application, proxy and CDN have all processed it — useful when local CSP configuration and production behaviour disagree.
Problem: a hash does not match
Hash-based CSP is byte-sensitive.
Common causes:
- whitespace changed;
- minifier changed output;
- newline added/removed;
- template engine changed quoting;
- hash calculated before final build transform;
- CDN modifies HTML;
- wrong algorithm (
sha256vssha384etc.); - external script missing matching SRI
integritymetadata where required.
Calculate the hash from the exact final script/style content the browser receives.
Do not hash the TypeScript source file and expect it to match a minified inline JavaScript block.
Problem: nonce is visible in DevTools — is that a vulnerability?
No, not by itself.
The nonce must be delivered to the browser so the browser can compare it with trusted elements.
Its security property is unpredictability before and during the injection opportunity, not permanent secrecy from the user who received the page.
The real bugs are things like:
- nonce reused across cached responses;
- predictable nonce generation;
- attacker-controlled elements automatically receiving the nonce;
- nonce exposed in a way an injection gadget can capture and reuse before execution.
Do not spend effort hiding it from DevTools.
Problem: browser reports unsafe-eval
Find the code path.
Possible causes:
- development framework runtime;
- source-map/debug tooling;
- an old template compiler;
- A/B testing vendor;
- code editor;
- WebAssembly tooling;
- dependency using
new Function().
If production genuinely needs WebAssembly compilation, investigate the narrower:
'wasm-unsafe-eval'
rather than granting JavaScript string evaluation wholesale.
If a library requires ordinary eval(), decide whether to upgrade, configure or replace it before adding 'unsafe-eval' permanently.
Problem: browser says strict-dynamic has no valid nonce or hash
MDN’s current CSP error guidance explicitly calls out this condition.
A policy such as:
script-src 'strict-dynamic'
without a nonce/hash trust root is not a meaningful strict CSP and may block scripts unexpectedly.
Use:
script-src 'nonce-{NONCE}' 'strict-dynamic'
or an appropriate hash-based root.
strict-dynamic propagates existing trust; it does not create trust from nothing.
Problem: default-src 'self' didn’t protect form submissions
That is expected.
form-action does not simply inherit default-src.
If you need to constrain form targets:
form-action 'self'
Declare it explicitly.
The same general lesson applies to frame-ancestors: do not assume every security-relevant directive participates in the fetch-directive fallback model.
Problem: block-all-mixed-content warning/deprecation
Old policies often contain:
block-all-mixed-content
Current guidance marks this directive obsolete/deprecated because modern mixed-content rules already upgrade or block the relevant resources.
Remove cargo-cult directives during policy review.
If legacy URLs need help migrating, upgrade-insecure-requests has a clearer current role — while still not replacing HSTS or fixing source URLs permanently.
Problem: upgrade-insecure-requests broke a resource
The browser rewrites:
http://legacy.example/file
to:
https://legacy.example/file
If the server does not support HTTPS, the request fails.
There is no fallback to HTTP.
Check the upgraded URL directly and fix the resource origin or source markup.
Problem: report-only policy produces no reports
A report-only policy without a reporting destination can observe violations in DevTools but cannot send useful telemetry to your server.
Check:
Reporting-Endpointsheader;report-togroup name;- legacy
report-uriif supporting older clients; - endpoint HTTPS/reachability;
- browser Reporting API behaviour;
- server request logs;
- privacy/ad-blocking interference.
Do not assume “no reports” means “no violations”.
Problem: report volume is enormous
Classify before changing policy.
Group by:
effective directive
blocked origin
route
browser
release
source file
Then separate:
real app dependency
browser extension
known scanner
old cached client
malware/user script
attack attempt
unknown
Do not add chrome-extension://-style noise to CSP to make a dashboard look cleaner.
Problem: only one user/browser sees the failure
Check:
- browser version;
- extensions;
- corporate proxy/security software;
- cached HTML/service worker;
- A/B test cohort;
- regional CDN variation;
- old app version in a long-lived tab;
- CSP browser compatibility.
CSP is evaluated client-side, so two users can receive or execute subtly different environments even when the server release is identical.
Problem: only production sees the failure
This usually points at infrastructure differences.
Compare:
local production
-------------------------------------------------
no CDN CDN header rules
one app server reverse proxy + WAF
no caching HTML cache
localhost API separate API origin
no analytics production analytics
no payments real payment provider
fresh browser long-lived clients
Fetch the public page with headers and compare it against your production-like local/staging environment.
Treat the infrastructure path as part of the application.
Problem: one route behaves differently
Check whether headers are configured globally.
It is common to apply CSP only to:
/
/app/*
while forgetting:
/login
/error
/404
/auth/callback
/admin
static HTML responses
edge-rendered routes
MDN’s CSP guidance recommends setting the policy on all relevant responses, not just the main document you happened to test.
Use route inventory or automated header tests.
Build a minimal reproducer before loosening the policy
If a complex framework page is failing, isolate the behaviour.
For example:
<!doctype html>
<meta charset="utf-8">
<script nonce="ABC" src="/loader.js"></script>
with:
Content-Security-Policy: script-src 'nonce-ABC' 'strict-dynamic'
Then add the failing mechanism incrementally.
A minimal reproduction helps separate:
- browser CSP semantics;
- framework behaviour;
- third-party code;
- infrastructure/header bugs.
That is usually faster than repeatedly editing a 1,500-character production policy.
Keep a known-good policy version
CSP should be versioned and deployable like code.
If release csp-v7 breaks production, you should be able to restore csp-v6 without reconstructing the old string from logs.
Store policy configuration in source control or controlled infrastructure configuration.
Avoid one-off manual edits in CDN dashboards that nobody can reproduce.
Add automated header assertions
A simple integration test can verify:
GET /
-> Content-Security-Policy exists
-> does not contain unexpected unsafe-eval
-> contains required frame-ancestors
-> contains report endpoint if expected
For nonce pages, a browser test can additionally verify:
CSP nonce == trusted script nonce
and run critical journeys while failing on unexpected CSP console violations.
That moves common production errors into CI.
The five-minute CSP debugging routine
Read the effective directive, inspect the document response headers, identify the feature that made the request, check whether multiple policies exist, then decide whether the behaviour deserves permission. Do those five things before editing the header.
Browse SiteTidy's security toolsA practical debugging decision tree
CSP error
│
▼
Which effective directive?
│
▼
Is the behaviour intentional?
├── NO -> remove/fix initiating code; do not allow it
│
└── YES
│
▼
Was a more specific directive omitted?
├── YES -> add narrow directive
│
└── NO
│
▼
Is trust supposed to come from nonce/hash?
├── YES -> fix nonce/hash propagation
│
└── NO
│
▼
Is source/origin permission genuinely required?
├── YES -> add narrow source
└── NO -> redesign/investigate
Then test the complete user journey again.
Final thought
The fastest CSP debugger is not the person who knows the most directives by memory.
It is the person who refuses to guess.
The browser normally tells you which policy decision failed. Your job is to connect that decision back to a real application behaviour and decide whether the application or the policy is wrong.
Once you work that way, CSP stops being a frustrating wall of console errors and becomes what it was meant to be: an explicit, testable description of the browser behaviour your application trusts.
Part 10 closes the series with the operational side: how to keep a strong CSP strong after launch — ownership, regression tests, policy drift, third-party changes, reporting, periodic review and a production hardening checklist you can actually use.
