Content Security Policy
Content Security Policy is an HTTP header (or <meta>) that tells the browser which scripts, styles, images, and connections a page may use. It is the main defence-in-depth against XSS.
Detailed Explanation
XSS runs because the browser treats a string as script. CSP says "only run script from these places". A strict policy uses script-src 'self' plus hashes or nonces for the few inline scripts you truly need. 'unsafe-inline' disables the protection for scripts. 'unsafe-eval' allows eval and new Function.
The header is Content-Security-Policy: .... Directives are ;-separated: default-src, script-src, style-src, img-src, connect-src (fetch/XHR/WebSocket), frame-ancestors (clickjacking), base-uri, form-action. Content-Security-Policy-Report-Only logs violations without blocking, which is how you roll out.
A nonce is a random per-response value: script-src 'nonce-abc' and <script nonce="abc">. A hash is sha256-... of the inline body. Both beat 'unsafe-inline'.
CSP does not replace output encoding. A missing escape in innerHTML is still a bug. CSP makes the payload fail to execute if it cannot load a script from an allowed origin.
What it costs you: third-party tags, inline event handlers (onclick="..."), and eval-based source maps in dev. Google Analytics, embeds, and hot reloading need connect-src and script-src entries. A too-tight policy breaks the app; a too-loose policy is theatre.
Reach for a nonce-based CSP on every HTML response. Reach for connect-src that lists your APIs. Reach for report-only first in production if you inherited a pile of inline scripts.
strict-dynamic plus a nonce lets trusted scripts load their own children without listing every CDN host. It is the modern path for third-party tags you cannot hash. Pair it with script-src-attr 'none' so inline event handlers stay dead.
Report URIs (report-uri / report-to) need an endpoint that will not store tokens from the document URI. Treat reports as untrusted input. A flood of reports after a release is usually your own inline style, not an attacker.
Code Examples
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-R4nd0m'; connect-src 'self' https://api.example.com; object-src 'none'; base-uri 'self'; frame-ancestors 'none'<script nonce="R4nd0m">
window.__BOOT__ = { user: null };
</script>document.addEventListener("securitypolicyviolation", (event) => {
console.warn(event.violatedDirective, event.blockedURI);
});Common Gotchas
`'unsafe-inline'` in `script-src` guts XSS protection
use nonces or hashes.
`eval` and `new Function` need `'unsafe-eval'`
remove them instead of loosening the policy.
Meta CSP cannot set `frame-ancestors`
that directive must be an HTTP header.