CSP is the most powerful browser-level defense against XSS attacks. At Google, every application has a strict CSP.
What is CSP?
A Content Security Policy tells the browser which resources are allowed to load and execute. If an attacker injects a script, the browser blocks it.
Setting CSP
Directive Reference
| Directive | Controls | Example |
|---|---|---|
| default-src | Fallback for all | 'self' |
| script-src | JavaScript | 'self' 'nonce-abc' |
| style-src | CSS | 'self' 'unsafe-inline' |
| img-src | Images | 'self' data: https: |
| connect-src | Fetch/XHR/WS | 'self' https://api.example.com |
| font-src | Fonts | 'self' https://fonts.gstatic.com |
| frame-src | iframes | 'none' |
| frame-ancestors | Who can frame you | 'none' (prevents clickjacking) |
Nonce-Based CSP (Recommended)
Strict CSP Template
Report-Only Mode
Common Pitfalls
- Never use
'unsafe-eval'— it defeats CSP's purpose 'unsafe-inline'for scripts is dangerous — use nonces instead'strict-dynamic'allows dynamically created scripts by trusted scripts- Always include
frame-ancestors 'none'to prevent clickjacking