AI QA Monkey
AI Security Intelligence
Fix Guide

Content-Security-Policy: Deploy It Without Breaking Your Site

Content-Security-Policy is the most effective header you can deploy against cross-site scripting, and the one most likely to break your site if you deploy it carelessly. That combination explains what we see in scan results: a great many sites have no CSP at all, and a large share of those that do have one written so permissively that it provides no protection.

This guide is the staged rollout we recommend — safe at every step, with nothing to roll back.

What CSP Actually Does

A Content-Security-Policy is an allowlist you hand the browser: these are the only places code and content may come from on my pages. Anything else is refused before it executes.

The reason this matters is the nature of XSS. An injection attack works because the browser cannot distinguish the script you wrote from the script an attacker injected — both arrive in the same HTML, from the same trusted origin. CSP gives the browser a way to tell them apart: your script carries proof of authorship, injected script does not.

Without CSP, a single injection flaw means arbitrary code execution in your users' browsers. With a strict CSP, that same flaw is frequently reduced to a blocked-resource message in the console.

It is a mitigation, not a cure — it limits what an injection can accomplish, and does not remove the need to encode output correctly. Think seatbelt, not brakes. But it is the difference between a bug and an incident.

Why unsafe-inline Cancels the Whole Policy

This is the most consequential thing to understand, and the finding our scanner raises most often against sites that do have a policy.

A policy such as this one looks configured and is worth almost nothing:

# Present, plausible, and provides essentially no XSS protection
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'

The entire mechanism rests on the browser refusing to execute script it cannot verify as yours. 'unsafe-inline' instructs it to run any inline script it encounters — which necessarily includes the script an attacker injected, because injected script is inline script. The policy still blocks a few things (external scripts from other origins), but against the attack CSP exists to stop, it stands down.

'unsafe-eval' is the related weakness: it permits eval(), new Function(), and string-argument timers, all of which turn attacker-controlled text into executing code.

The way out is not to remove your inline scripts — it is to prove which inline scripts are yours, using nonces or hashes. That is Stage 4.

Report-Only is not enforcement

A second common finding: a site sends only Content-Security-Policy-Report-Only and believes it is protected. Report-only mode blocks nothing — it is a measurement tool. It is exactly the right place to start and the wrong place to stop, and it is easy to forget a report-only header that has been quietly running for a year.

Stage 1: Inventory What You Load

Before writing a policy, find out what your pages genuinely depend on. Open a representative page — ideally your most complex one, such as a checkout — and work through the Network tab by type. You are looking for every origin that serves:

  • Scripts — analytics, tag managers, chat widgets, payment SDKs, A/B testing, error monitoring
  • Styles — CSS frameworks, font providers, injected widget styles
  • Fonts — often a different origin from the stylesheet that requests them
  • Images — CDNs, user uploads, tracking pixels, data: URIs
  • Frames — payment iframes, embedded video, social widgets
  • Connections — the origins your JavaScript calls via fetch, XHR or WebSocket

The item people miss: a tag manager is not one origin. It is a loader that injects further scripts at runtime, each from origins that may change without any deployment on your side. This is precisely why the next stage exists — a manual inventory will always be incomplete, and real traffic will tell you the truth.

Stage 2: Ship Report-Only

Deploy your first draft as Content-Security-Policy-Report-Only. The browser evaluates the identical policy, blocks nothing, and sends a JSON report every time it would have blocked something.

Content-Security-Policy-Report-Only:
  default-src 'self';
  script-src 'self' https://cdn.example.com;
  style-src 'self' https://fonts.googleapis.com;
  font-src 'self' https://fonts.gstatic.com;
  img-src 'self' data: https:;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  object-src 'none';
  base-uri 'self';
  report-uri /csp-report;
  report-to csp-endpoint

Include both report-uri and report-to: the former is deprecated but still the more widely honoured of the two, and the latter is the modern replacement. Sending both maximizes the reports you actually receive.

A minimal collector — log everything, deduplicate later:

<?php
// /csp-report.php — accepts violation reports from the browser
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
if ($data) {
    // Store, do not echo. Reports are attacker-influenceable input.
    error_log('[CSP] ' . json_encode($data['csp-report'] ?? $data));
}
http_response_code(204);

Run it for at least a week. Long enough to cover your weekly traffic cycle, a marketing campaign, and whatever your team ships in a normal sprint. Enforcing after a day is how teams discover that their invoice page — used only at month end — breaks in production.

Stage 3: Read the Reports

Reports arrive noisy. Triage each one into a category, because they demand different responses:

  1. Genuine dependencies. Real resources your site needs. Add the origin to the appropriate directive — as narrowly as possible. Prefer https://cdn.example.com over https://*.example.com, and never fall back to *.
  2. Browser extensions. Reports with chrome-extension:, moz-extension: or safari-extension: in the blocked URI are the user's extensions, not your site. Filter them out; they are unfixable and will otherwise drown the signal.
  3. Things you should delete. The rollout's hidden benefit. Analytics from a vendor you stopped paying two years ago, a chat widget from a retired experiment, a font from a redesign that never shipped. Every one of these is live third-party code on your pages. Remove them rather than allowlisting them — see our supply-chain guide for why this matters more than it appears.
  4. Your own inline code. The largest category on most sites, and the subject of the next stage.

Stage 4: Replace unsafe-inline With Nonces

A nonce is a random value generated fresh for every single response. You place it on the inline scripts you control and name it in the policy; the browser executes only inline scripts carrying that exact value. An attacker injecting script cannot guess it — and because it changes every request, they cannot reuse a value seen earlier.

<?php
// Generate ONE nonce per response, before any output
$nonce = base64_encode(random_bytes(16));

header("Content-Security-Policy: "
     . "default-src 'self'; "
     . "script-src 'self' 'nonce-{$nonce}'; "
     . "style-src 'self'; "
     . "object-src 'none'; "
     . "base-uri 'self'");
?>
<!-- Every inline script you own carries the nonce -->
<script nonce="<?= htmlspecialchars($nonce, ENT_QUOTES) ?>">
  initialiseApp();
</script>

Three rules that make nonces safe, all of which are violated regularly:

  • Cryptographically random, minimum 128 bits. random_bytes(16), crypto.randomBytes(16) — never rand(), a timestamp, or a session-derived value.
  • Fresh on every response. A nonce reused across requests, or baked into a cached page, is equivalent to unsafe-inline with extra steps.
  • Never on a cached page. If a full-page cache or CDN serves the same HTML to many users, the nonce is shared and therefore worthless. Either exclude the header from caching and vary it at the edge, or use hashes instead.

The static-site alternative: hashes. When there is no server to generate a per-request value, fingerprint the script content instead. The browser hashes each inline script and runs only those whose hash is listed:

# Compute the hash of the exact inline script content
echo -n "initialiseApp();" | openssl dgst -sha256 -binary | openssl base64

# Then reference it in the policy
Content-Security-Policy: script-src 'self' 'sha256-Ku3aOMH4gRlIuAd4v4l1gCbFjEXTQ0qhWFpFbBMxSy0='

Hashes are exact: change one character of the script, including whitespace, and it stops running. That fragility is manageable in a build pipeline that computes them automatically, and painful if maintained by hand.

When you have too many third-party scripts to list

'strict-dynamic' changes the model: scripts you have explicitly trusted with a nonce may load further scripts, which inherit that trust, while allowlisted origins are ignored. This is the practical answer for sites with tag managers that inject unpredictable chains. It is a real trade-off — you are trusting your tag manager's entire downstream — so adopt it deliberately, not as a shortcut around Stage 3.

Stage 5: Enforce

When reports have been quiet for several days and every remaining violation is extension noise, switch on enforcement. The change is one header name:

# Before
Content-Security-Policy-Report-Only: default-src 'self'; …

# After
Content-Security-Policy: default-src 'self'; …

Keep the reporting endpoint attached after enforcement. It becomes your early warning system: the first sign that a developer added a script without updating the policy — or that someone injected one — is a violation report. Turning off reporting at enforcement removes the visibility exactly when it becomes most useful.

A safe pattern for large sites is to enforce progressively: start with a low-risk section, then expand. Running an enforced policy and a stricter report-only policy simultaneously is also valid, and is how you test the next tightening without risk.

The Directives That Earn Their Place

Beyond script-src, four directives deliver protection out of proportion to their length:

  • frame-ancestors 'none' — prevents your pages being embedded in an iframe on another site, which is the modern, more capable replacement for X-Frame-Options and the correct defence against clickjacking. Use 'self' if you embed your own pages.
  • object-src 'none' — blocks <object>, <embed> and legacy plugin content, a historically rich source of bypasses. Essentially no modern site needs these.
  • base-uri 'self' — prevents an injected <base> tag rewriting every relative URL on the page to an attacker's origin. Cheap, and closes a bypass that defeats otherwise strong policies.
  • form-action 'self' — stops an injected form posting your users' input to an external endpoint. Frequently overlooked, and directly relevant to credential theft.

A solid modern target policy, worth aiming for:

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-{RANDOM}' 'strict-dynamic';
  style-src 'self' 'nonce-{RANDOM}';
  img-src 'self' data: https:;
  font-src 'self';
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  form-action 'self';
  base-uri 'self';
  object-src 'none';
  upgrade-insecure-requests;
  report-uri /csp-report

Configuration by Platform

Nginx — note always, without which the header is omitted on error responses:

add_header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" always;

Apache — .htaccess or vhost:

<IfModule mod_headers.c>
  Header always set Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"
</IfModule>

Express — via Helmet, with a per-request nonce:

app.use((req, res, next) => {
  res.locals.nonce = crypto.randomBytes(16).toString("base64");
  next();
});

app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", (req, res) => `'nonce-${res.locals.nonce}'`],
    objectSrc: ["'none'"],
    baseUri: ["'self'"],
    frameAncestors: ["'none'"]
  }
}));

Next.js — middleware generating a nonce per request:

// middleware.js
export function middleware(request) {
  const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
  const csp = `default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'self'`;
  const headers = new Headers(request.headers);
  headers.set("x-nonce", nonce);
  const response = NextResponse.next({ request: { headers } });
  response.headers.set("Content-Security-Policy", csp);
  return response;
}

WordPress — in your theme's functions.php:

add_action('send_headers', function () {
    header("Content-Security-Policy: default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'");
});

Five Traps That Catch Experienced Teams

  1. The meta tag cannot do everything. <meta http-equiv="Content-Security-Policy"> works, but frame-ancestors, report-uri and sandbox directives are ignored in meta form. Deliver the policy as an HTTP header.
  2. A missing directive falls back to default-src — except when it does not. frame-ancestors, base-uri, form-action and report-uri do not inherit from default-src. Omitting them means no restriction at all, not a restrictive default.
  3. Two CSP headers intersect, they do not merge. If your application and your CDN each set a policy, the browser enforces both, and a resource must satisfy every policy. This is a common cause of "it works on staging" — where only one layer is present.
  4. Nonces and full-page caching are incompatible. A cached page serves one nonce to thousands of users, which is no better than unsafe-inline. Vary the header at the edge, or use hashes for cached content.
  5. Inline event handlers are inline script. onclick="…", onload="…" and javascript: URLs cannot be nonced and are blocked by any strict policy. Move them to addEventListener in a nonced script. On legacy codebases this is usually the largest slice of the work — plan for it rather than discovering it at enforcement.

See Your Current CSP — and What It Actually Blocks

Our scanner parses your policy for unsafe-inline, unsafe-eval, wildcard sources and report-only-without-enforcement, alongside the other nine security headers — free, in about 60 seconds.

Scan Your Site Now

Frequently Asked Questions

Why is unsafe-inline dangerous?

It removes the protection CSP exists to provide. The header defends against XSS by refusing to run script the browser cannot verify as yours; 'unsafe-inline' tells it to run any inline script, including injected script. A policy containing it offers essentially no XSS protection despite appearing configured. Use nonces or hashes instead.

What is the difference between a nonce and a hash?

A nonce is random, generated per response, and placed on your script tags — it needs server-side rendering. A hash is a fixed fingerprint of exact script content, listed in the policy — it suits static sites but breaks when the content changes by one character. Nonces for dynamic pages, hashes for static output.

Should I start with Report-Only?

Always. It applies the identical policy but blocks nothing, reporting what would have been blocked. That reveals every real dependency — including scripts injected at runtime by tag managers — with no risk to production. Enforcing a first draft is the most common cause of a CSP rollback.

Does CSP replace fixing XSS?

No. It limits what an injection can achieve; it does not remove the need for correct output encoding and input validation. Seatbelt, not brakes — it dramatically reduces impact, but the flaw still needs fixing.

How long does a realistic CSP rollout take?

For a straightforward site, a few hours of work spread over a week of report-only observation. For a large application with legacy inline handlers and several marketing tools, plan for a few weeks — most of it spent removing inline event handlers and negotiating which third-party scripts genuinely need to stay.

Check Your Website Right Now

Run a free automated security scan — 100 checks in 60 seconds. No signup required.

Run Free Security Scan →