Content Security Policy (CSP) is an HTTP header that tells browsers which resources (scripts, styles, images) are allowed to load on your page. It's the strongest defense against XSS attacks — even if an attacker injects a script tag, the browser blocks it because it's not in the CSP allowlist.

How Content Security Policy Works

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'; img-src *. This allows scripts only from your domain and cdn.example.com, styles from your domain (plus inline), and images from anywhere.

Key Concepts

  • Directives — Rules specifying allowed sources per resource type — script-src, style-src, img-src, default-src
  • Report-Only Mode — Test your CSP without blocking — violations are reported but not enforced

Frequently Asked Questions

Is CSP hard to implement?

Start with report-only mode to identify violations, then tighten gradually. Framework-specific guides exist for React, Next.js, and other stacks.