What Is CSP (Content Security Policy)?
Content Security Policy (CSP) is an HTTP security header that controls which resources a browser is allowed to load for a page. It is one of the most effective defenses against cross-site scripting (XSS) and data injection attacks.
How CSP Works
The server sends a Content-Security-Policy header with a set of directives that define allowed sources for different resource types. For example, script-src 'self' https://cdn.example.com only allows scripts from the same origin and the specified CDN. If any script tries to load from another source, the browser blocks it.
Key CSP Directives
default-src sets the fallback for all resource types. script-src controls JavaScript sources. style-src controls CSS sources. img-src controls image sources. frame-ancestors controls which sites can embed your page in iframes, replacing X-Frame-Options.
Why CSP Matters
XSS is consistently one of the most common web vulnerabilities. CSP provides a strong defense-in-depth layer by preventing browsers from executing unauthorized scripts — even if an attacker manages to inject script tags into your page. CSP also prevents unauthorized data exfiltration by restricting where the browser can send data.
Frequently Asked Questions
What does CSP protect against?
CSP primarily prevents XSS attacks by controlling which content sources the browser loads. It also mitigates clickjacking, data injection, and mixed content issues.
How do I implement CSP?
Add a Content-Security-Policy HTTP response header. Start with report-only mode to monitor violations without breaking your site, then switch to enforcement once the policy is refined.
What is CSP report-only mode?
Report-only mode logs violations without blocking them, letting you test a policy on a live site. Use Content-Security-Policy-Report-Only and the report-uri directive to collect violation reports.