Content Security Policy is a browser-enforced allowlist telling the browser exactly which sources of scripts, styles, and other resources a page is allowed to load — a genuinely powerful defense-in-depth layer against XSS.
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.trusted-analytics.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.myapp.com; frame-ancestors 'none';
Why This Matters Even If You Already Escape Output
Escaping user input properly should prevent XSS in the first place — CSP is a second, independent layer that limits the damage if a script somehow gets injected anyway, whether through a bug, a compromised third-party script, or a dependency vulnerability. Even with a script successfully injected, CSP can block it from executing at all if its source isn’t on the allowlist.
Building a Policy Without Breaking Your Site
# Test in report-only mode first - logs violations without actually blocking anything Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-violations
Rolling out a strict CSP directly to production risks silently breaking legitimate functionality (an analytics script, a font loaded from a CDN) — Content-Security-Policy-Report-Only mode logs what would have been blocked without actually blocking it, letting you refine the policy against real traffic before enforcing it.