Apply Content Security Policy (CSP) in Stages
Content Security Policy (CSP) is a set of browser-enforced rules sent by a server to restrict which scripts a page may execute and which resources it may load. It does not replace output encoding or safe DOM handling, but it can limit the impact of XSS by blocking scripts that the policy does not authorize. Inventory real page behavior, observe a candidate policy with Report-Only, then enforce a narrow policy built around nonces or hashes.
What CSP controls
The preferred delivery mechanism is the Content-Security-Policy HTTP response header. The browser evaluates directives such as script-src, img-src, and connect-src as it processes a document. default-src supplies a fallback source list for some fetch directives when a more specific directive is absent. 'self' means the document's own origin; 'none' allows no source. Multiple policies are all enforced, so adding a second policy cannot loosen an existing one. W3C CSP Level 3
CSP is a backup restriction, not a substitute for fixing unsafe HTML output or DOM manipulation. Keep context-appropriate output encoding, trusted HTML sanitization, and safe DOM APIs. Broad host allowlists can trust executable scripts hosted on shared, stale, or user-controlled services. OWASP CSP Cheat Sheet
Choose an allowlist, nonce, or hash
Host allowlists are easy to start with, but each permitted host expands the trust boundary. A strict CSP authorizes the scripts a page actually needs rather than trusting broad domains.
A nonce fits dynamically generated HTML. The server creates a fresh, unpredictable value for each response and puts it in both the policy and approved <script> elements. Keep the header and HTML cache in sync. Never add a nonce afterward to every script element: that could authorize injected scripts too.
A hash fits static or rarely changed inline scripts. The policy lists a SHA-256, SHA-384, or SHA-512 digest; the browser checks the exact script content. Any content change, including whitespace, requires a new hash and deployment verification.
| Method | What it trusts | Suitable when | Main caution |
|---|---|---|---|
| Host allowlist | Resources from named hosts | A legacy app cannot yet use a strict policy | Broad or shared hosts enlarge trust |
| Nonce | Approved scripts marked in this response | HTML is generated dynamically | Generate per response and keep values aligned |
| Hash | Exact script content named in the policy | Inline code is static | Recalculate after every content change |
strict-dynamic can extend trust from a nonce- or hash-authorized script to scripts it loads, so review the loader's URL decisions. Check target-browser support. Avoid casually adding broad https:, 'unsafe-inline', or 'unsafe-eval' exceptions; refactor inline handlers and string-evaluation dependencies where possible. MDN strict CSP guide
Observe first, then enforce
Content-Security-Policy-Report-Only reports policy violations without blocking the resource. Exercise real routes and logged-in workflows, then distinguish expected integrations from mistakes. A report is a signal to investigate, not proof of an attack; extensions and third-party code can also trigger violations. Limit duplicate reports and collect only the information needed because reports may contain page URLs or browsing context. W3C Report-Only header
The following is an illustrative assumption, not a ready-to-copy policy. {RESPONSE_NONCE} is a placeholder: production must generate a new value per document response.
Content-Security-Policy-Report-Only: default-src 'none'; script-src 'nonce-{RESPONSE_NONCE}' 'strict-dynamic'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'Adapt each directive after checking APIs, image/font hosts, payment and sign-in flows, and whether embedding is needed. frame-ancestors controls who may frame this page; frame-src controls frames this page loads. They are not interchangeable, and frame-ancestors cannot be set with a meta policy. After resolving violations, send the policy as an enforced Content-Security-Policy header. Switching back to Report-Only stops blocking and changes the protection level.
Review directives and common mistakes
script-src governs scripts, style-src styles, img-src images, and connect-src connections such as Fetch, XHR, and WebSocket. object-src 'none' blocks unused embedded objects; base-uri 'none' prevents a <base> element from changing relative URL resolution. form-action limits form destinations; frame-ancestors limits who can embed the page. Not every directive inherits from default-src, so check each directive's definition.
Common mistakes include treating Report-Only as enforcement; reusing a nonce or allowing cache to mismatch the header and HTML; adding 'unsafe-inline', 'unsafe-eval', wildcards, or broad hosts just to silence violations; confusing frame-src with frame-ancestors; and collecting unbounded reports. Roll out on real feature paths, refactor disallowed patterns, enforce the reviewed policy, and monitor console errors and reports. CSP does not fix XSS at its source, and browser behavior can differ; test the browsers you support.
References
[MDN: CSP implementation guide](https://developer.mozilla.org/en-US/docs/Web/Security/Practical_implementation_guides/CSP)
[OWASP Content Security Policy Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Content_Security_Policy_Cheat_Sheet.html)
[W3C Content Security Policy Level 3](https://www.w3.org/TR/CSP/)