Security · Response header
Content-Security-Policy
The primary defense against XSS: whitelist trusted sources.
What is Content-Security-Policy?
CSP tells the browser which sources of scripts, styles, images, and other resources are allowed. A tight CSP can neutralize most XSS attacks even if an injection happens.
Typical usage
Set on all HTML responses for user-facing web apps.
Examples
Strict CSP
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; object-src 'none'Common gotchas
Introducing CSP breaks inline scripts and styles unless nonces or hashes are used. Roll it out in report-only mode first, then enforce.
Specification
W3C CSP Level 3
Related headers
Strict-Transport-Security
Force browsers to use HTTPS for a domain (HSTS).
X-Frame-Options
Prevents clickjacking by controlling framing.
X-Content-Type-Options
Disables MIME-type sniffing.
Referrer-Policy
Controls the Referer header sent on outgoing links and requests.
Permissions-Policy
Controls which browser features and APIs pages can use.