What it is
A Content Security Policy is an HTTP response header that tells the browser which sources of scripts, styles, images, and connections are allowed. It is a defense in depth layer against injection.
Key directives
- default src sets the fallback policy for most resource types.
- script src controls where JavaScript may load from and whether inline scripts run.
- connect src limits fetch, XHR, and WebSocket targets.
- frame ancestors controls who may embed your page.
Nonces and hashes
Allowing all inline scripts defeats the policy. Instead use a per response nonce or a hash of the script body. Only scripts carrying the matching nonce execute, so an injected inline script is blocked.
Strict CSP pattern
A modern strict policy uses strict dynamic with a nonce. Trust flows from the nonced script to any scripts it loads, which lets you drop fragile host allowlists.
Reporting
Use report only mode to collect violations without breaking the page, then enforce once clean.
Key idea
CSP whitelists trusted sources and uses nonces or hashes so injected scripts are blocked even when XSS exists.