What is a CSP header and do I need it?

Short answer

Content Security Policy (CSP) is an HTTP header that tells browsers which sources are allowed for scripts, styles, images, and frames. A strict CSP blocks most XSS attacks. Yes, you need it — it's one of the cheapest, highest-leverage security controls available.

CSP is a defense-in-depth layer. Even if an attacker injects a `<script>` into your page, a strict CSP prevents the browser from executing it.

Minimal strict CSP for a Next.js app: ``` Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123' 'strict-dynamic'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'; ```

Common mistakes: - `'unsafe-inline'` in script-src defeats most XSS protection - `*` in any source list is almost always too permissive - Forgetting `object-src 'none'` leaves Flash / Java plugins reachable - Missing `base-uri 'self'` allows base-tag injection attacks

Getting CSP right without breaking your app takes 2-4 hours of tuning. Deploy in report-only mode first: ``` Content-Security-Policy-Report-Only: <your policy> ``` Read violation reports for a week, then switch to enforcing.

Full guide: /guides/security-headers-next-js.

People also ask