CSP allows you to create a whitelist of sources from which scripts, styles, images, and other resources can be loaded. It prevents XSS by blocking inline scripts and restricting allowed origins. Even if an attacker injects a script, CSP will block it unless it matches your policy. A well‑configured CSP can stop almost all XSS attacks.
Before enforcing CSP, use `Content-Security-Policy-Report-Only`. This mode sends violations to a reporting endpoint without blocking anything. You'll see what would be blocked, allowing you to adjust your policy without breaking your site. Many developers use this mode for weeks to fine‑tune their policy.
The most important directives are `default-src` (fallback for all resources), `script-src` (scripts), `style-src` (styles), `img-src` (images), `connect-src` (AJAX, WebSockets), and `frame-ancestors` (clickjacking protection). Start with a restrictive policy like:
These directives completely bypass CSP protection. If you need inline scripts, use nonces: `