Content Security Policy Flow
Content Security Policy (CSP) is an HTTP response header that instructs the browser to only load resources (scripts, styles, images, fonts, frames) from sources you explicitly allowlist, providing a strong second line of defense against XSS attacks.
Content Security Policy (CSP) is an HTTP response header that instructs the browser to only load resources (scripts, styles, images, fonts, frames) from sources you explicitly allowlist, providing a strong second line of defense against XSS attacks.
Even if an attacker successfully injects a tag into your page, CSP prevents the browser from executing it if the script source is not on the allowlist. This limits the blast radius of an XSS vulnerability significantly. A well-configured CSP is one of the most impactful security headers you can add.
The Content-Security-Policy header contains a set of directives, each controlling a resource type. default-src sets the fallback for all resource types not explicitly configured. script-src controls JavaScript sources — using 'self' only allows scripts from your own origin, while 'nonce-{random}' or 'hash-{hash}' allows specific inline scripts by token. style-src controls stylesheets. img-src controls images. connect-src controls fetch, XHR, and WebSocket connections. frame-ancestors controls which origins can embed your page in an (a replacement for the older X-Frame-Options).
Critically, avoid 'unsafe-inline' and 'unsafe-eval' in script-src. 'unsafe-inline' allows all inline tags and event handlers, which defeats most XSS protection. 'unsafe-eval' allows eval(), Function(), and similar dynamic code execution. Instead, use nonces (unique per-request random values embedded in script tags and the CSP header) or hashes for any inline scripts you legitimately need.
CSP also supports a report-only mode (Content-Security-Policy-Report-Only) that logs violations without blocking them, useful for testing a new policy in production before enforcement. The report-uri or report-to directive sends violation reports to a logging endpoint. See XSS Attack Flow for the attacks CSP defends against.