Community
Content Security Policy Headers
CSP configuration for XSS prevention, inline script control, and reporting.
CLAUDE.md
# Content Security Policy Headers
You are an expert in Content Security Policy, browser security headers, and XSS prevention.
CSP Basics:
- CSP prevents XSS by controlling which resources the browser can load
- Set via Content-Security-Policy response header (not meta tag for full coverage)
- Start with a restrictive policy and loosen as needed
- Use Content-Security-Policy-Report-Only to test without blocking
- Each directive controls a specific resource type (scripts, styles, images, etc.)
Recommended Policy:
- default-src 'none': deny everything by default
- script-src 'self': allow scripts only from your origin
- style-src 'self': allow styles only from your origin
- img-src 'self' data: https:: allow images from your origin, data URIs, and HTTPS
- font-src 'self': allow fonts only from your origin
- connect-src 'self' https://api.yourdomain.com: allow fetch/XHR to your API
- frame-ancestors 'none': prevent clickjacking (replaces X-Frame-Options)
Inline Scripts & Styles:
- Avoid 'unsafe-inline' for scripts; it defeats the purpose of CSP
- Use nonce-based approach: script-src 'nonce-{random}' (generate per request)
- Use hash-based approach: script-src 'sha256-{hash}' for static inline scripts
- For styles, 'unsafe-inline' is sometimes necessary (CSS-in-JS frameworks)
- Use strict-dynamic for scripts that load other scripts (cascading trust)
Reporting:
- Set report-uri or report-to directive to collect violation reports
- Use a reporting service: Report URI, Sentry CSP, or custom endpoint
- Monitor reports to detect attacks and policy misconfigurations
- Start with Report-Only mode, fix violations, then enforce
Other Security Headers:
- Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
- X-Content-Type-Options: nosniff (prevent MIME sniffing)
- X-Frame-Options: DENY or SAMEORIGIN (legacy clickjacking prevention)
- Referrer-Policy: strict-origin-when-cross-origin
- Permissions-Policy: camera=(), microphone=(), geolocation=() (disable unused APIs)
Add to your project root CLAUDE.md file, or append to an existing one.