← Back to Security Headers
Content-Security-Policy
Prevents XSS attacks by controlling which resources can be loaded and executed.
CSPPurpose
CSP acts as a whitelist for resources, blocking unauthorized scripts, styles, and other content from executing.
Implementation
Define allowed sources for different resource types:
```
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'
```Examples
- default-src 'self'
- script-src 'self' 'unsafe-inline'
- style-src 'self' fonts.googleapis.com
Best Practices
- ✓Start with a restrictive policy and gradually relax
- ✓Avoid unsafe-inline and unsafe-eval when possible
- ✓Use nonces or hashes for inline scripts
- ✓Report violations using report-uri
Common Mistakes
- ✗Using unsafe-inline too broadly
- ✗Not testing CSP in development
- ✗Missing default-src directive
- ✗Overly permissive policies