What is a Content Security Policy? CSP Explained
XSS attacks work by injecting scripts into your page. CSP is a browser-enforced allowlist that controls which scripts, styles, and resources are allowed to run — blocking injected scripts even if they get into your HTML.
The problem CSP solves
Without CSP, if an attacker finds a way to inject <script src="https://evil.com/steal.js"></script> into your page, the browser runs it. With CSP, the browser checks if evil.com is in your allowlist — it is not, so the script is blocked.
How CSP works
Your server sends a Content-Security-Policy header with directives that define what is allowed. The browser enforces them when loading the page.
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com; style-src 'self' https://fonts.googleapis.com; img-src 'self' data: https:; frame-ancestors 'none'; object-src 'none';
The main directives
| Directive | Controls |
|---|---|
| default-src | Fallback for all resource types not explicitly listed |
| script-src | JavaScript files and inline scripts |
| style-src | CSS files and inline styles |
| img-src | Images |
| connect-src | XHR, fetch, WebSocket connections |
| font-src | Font files |
| frame-src | Iframes your page loads |
| frame-ancestors | Who can embed your page in an iframe |
| object-src | Plugins (Flash etc) — set to none |
Why unsafe-inline defeats CSP
Adding 'unsafe-inline' to script-src allows any inline script to run — including injected ones. It fixes the "inline script blocked" error but removes all XSS protection. Use nonces instead.
Start with report-only mode
Use Content-Security-Policy-Report-Only to test your policy without blocking anything. Violations appear in the browser console, letting you build your allowlist before enforcing.
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self';Generate a CSP for your page → CSPFixer