Content Security Policy is one of the most effective mitigations against cross-site scripting — not because it stops the injection, but because it limits what an injected script can actually accomplish.
What CSP restricts
CSP is a response header that tells the browser which sources are allowed for scripts, styles, images, fonts, and other resource types on a given page. A well-configured policy can block inline scripts entirely, restrict script loading to your own domain and specifically trusted third parties, and prevent the page from being framed by other sites.
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.example.com; object-src 'none'
Why this matters even if you've fixed your XSS bugs
CSP is defense in depth — it doesn't assume your application has no XSS vulnerabilities, it assumes it might, and limits the damage if one exists. Even a well-reviewed codebase can have an XSS bug slip through; CSP is what stands between that bug and an attacker successfully exfiltrating data or hijacking a session.
The unsafe-inline trap
Many sites end up allowing unsafe-inline for scripts because their existing codebase relies heavily on inline <script> tags or inline event handlers. This significantly weakens CSP's protection, since it's exactly what allows a typical injected XSS payload to execute. Migrating to external script files and CSP nonces or hashes closes this gap, though it often requires real refactoring for legacy codebases.
Nonces and hashes for necessary inline scripts
For cases where inline scripts are genuinely needed, CSP supports per-request nonces (script-src 'nonce-<random-value>') or content hashes, allowing specific, trusted inline scripts to run while still blocking arbitrary injected ones.
Rolling out safely
Deploying a strict CSP on an existing application risks breaking legitimate functionality that relied on now-blocked behavior. Start with Content-Security-Policy-Report-Only, which logs violations without enforcing them, letting you identify what needs adjustment before switching to full enforcement.
Don't treat it as a complete solution
CSP significantly raises the bar for exploiting XSS, but a sufficiently permissive policy, or a bypass in an allowed third-party script source, can still be exploited. It complements — not replaces — actually preventing injection through proper output encoding and input validation.