Cybersecurity & Privacy

What Is Content Security Policy? How CSP Actually Stops XSS Attacks

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

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