CSP is a response header that tells the browser which scripts, styles, frames and connections a page may use. Its main job is to stop injected markup from executing script, as a second line of defence after output encoding. Modern guidance favours a strict CSP: per-response nonces (or hashes) plus 'strict-dynamic', instead of brittle domain allow-lists, which are routinely bypassed through JSONP endpoints or script gadgets on allowed CDNs. Roll it out with Content-Security-Policy-Report-Only, collect violations, fix them, then enforce.
Content-Security-Policy:
script-src 'nonce-R4nd0mPerResponse' 'strict-dynamic' https: 'unsafe-inline';
object-src 'none';
base-uri 'none';
frame-ancestors 'self';
report-to csp-endpoint
<script nonce="R4nd0mPerResponse" src="/app.js"></script>
<script> doesn't have it, so it's blocked.'strict-dynamic': scripts loaded by a trusted (nonced) script are trusted too. This makes bundler chunks and tag managers work without listing their hosts. In browsers that support it, host allow-lists and 'unsafe-inline' are ignored, so https: and 'unsafe-inline' are only fallbacks for very old browsers.object-src 'none' blocks plugin-based bypasses. base-uri 'none' stops <base href> injection from redirecting relative script URLs.frame-ancestors replaces X-Frame-Options for clickjacking defence. It can't be set via a <meta> tag.'sha256-…') of inline scripts instead.<script> blocks, inline event handlers (onclick=), javascript: URLs, eval/new Function (including in libraries and some template engines), third-party tags.addEventListener, add nonces through your SSR or edge layer, and remove eval usage (or accept 'unsafe-eval' temporarily and track it as debt).require-trusted-types-for 'script' later to harden DOM sinks (Chromium has supported Trusted Types for years, and other engines have been adding support, so check current coverage).Reporting: report-to with a Reporting-Endpoints header is the modern mechanism. report-uri is deprecated but still more widely supported, so sending both is common.
| Directive | Use |
|---|---|
connect-src | Limit fetch/XHR/WebSocket destinations, which limits exfiltration |
img-src, style-src, font-src | Tighter resource control. Style injection can still leak data, so lock it down where practical |
upgrade-insecure-requests | Rewrites http: subresources to https: during migrations |
form-action | Stops injected forms posting credentials elsewhere |
sandbox | Applies iframe-like sandboxing to the page itself |
'unsafe-inline' without a nonce or 'strict-dynamic', which defeats the point.*.googleapis.com that host JSONP or Angular-style gadgets.strict-dynamic) vs allow-lists, and why allow-lists fail.frame-ancestors, base-uri, object-src as the cheap must-haves.Spotted a mistake or a rights concern? Report an issue