CSP tells browsers which origins may run scripts, load styles, embed frames, etc. It is a strong second line of defense after escaping output.

Basic directive shape

Content-Security-Policy: default-src 'self'; img-src 'self' data: https:; style-src 'self'

Scripts without inline eval

  • Avoid 'unsafe-inline' in script-src in production.
  • Use nonce per response on <script> tags: script-src 'nonce-{random}'.
  • Or sha256 hashes for tiny inline snippets.

Clickjacking

frame-ancestors 'none' or allowlist parents instead of legacy X-Frame-Options alone.

Rollout

Start with Content-Security-Policy-Report-Only and collect violations before enforcing.

Common pain

Third-party analytics/widgets require explicit allowlists; inline event handlers (onclick=) violate strict CSP — refactor to JS files.