What XSS Actually Is
Cross-site scripting (XSS) happens when an attacker manages to inject their own JavaScript into a page — through a comment field, a URL parameter, or any input that ends up rendered without proper handling. If that injected script runs in a victim's browser, it executes with the same trust and access as the site's own legitimate code, able to steal session data, redirect the page, or manipulate content.
A Response Header, Not a Code Fix
Content Security Policy is an HTTP header your server sends alongside a page, telling the browser exactly which sources of scripts, styles, and other resources are allowed to execute. It's a browser-enforced allowlist — even if malicious script somehow gets injected into the page's HTML, the browser refuses to execute it unless it comes from a source your policy explicitly trusts.
The Specific Mechanisms That Block XSS
- Blocking inline scripts by default: once a
script-srcdirective is set, inline<script>tags and inline event handlers (likeonclick) are blocked unless explicitly allowed — and since most XSS attacks rely on injecting exactly this kind of inline script, this alone eliminates a large share of possible attacks. - Blocking
eval()and similar functions: CSP blockseval(), string-basedsetTimeout/setInterval, andnew Function()by default — closing off code-injection vectors that work through dynamic code evaluation rather than a literal script tag. - Source allowlisting: only scripts loaded from origins your policy explicitly names are permitted to run at all.
Why This Is Defense in Depth, Not a Replacement
CSP is a powerful browser-level backstop, but it works best alongside — not instead of — proper input validation and output encoding in your actual application code. If an injection vulnerability exists, CSP can prevent it from succeeding even so; but a correctly written application that never allows the injection in the first place is still the foundational layer CSP is reinforcing.
Ready to add this protection to your site?
Open CSP Generator