CSP (Content Security Policy)
An HTTP response header policy that restricts which scripts, styles, frames, and network origins a browser is allowed to load or execute, mitigating XSS
Table of Contents
Structure Diagram
What is CSP (Content Security Policy)?
An HTTP response header policy that restricts which scripts, styles, frames, and network origins a browser is allowed to load or execute, mitigating XSS. It is a core concept in Auth & Security within Web Dev.
Core Principles
Content Security Policy (CSP) is a browser-enforced defense-in-depth layer that neutralizes XSS even if an injection bug slips into your code. Delivered via the Content-Security-Policy HTTP header, directives like script-src, connect-src, img-src, and frame-ancestors tell the browser exactly which origins and scripts are trusted.
Setting frame-ancestors 'none' also replaces legacy X-Frame-Options to block Clickjacking attacks.
Practical Takeaways
- Roll out with
Report-Onlyfirst: Enabling strict CSP blindly can break analytics or payment iframes. DeployContent-Security-Policy-Report-Onlywith a reporting endpoint to audit violations before enforcing. - Avoid
'unsafe-inline'— use Nonces and'strict-dynamic': Allowing'unsafe-inline'largely defeats XSS protection. Generate a per-request cryptographic nonce for trusted<script>tags under a Strict CSP. - Lock down exfiltration with
connect-src: Restrictingfetch/WebSocketdestinations stops compromised scripts from beaming data to attacker domains.
Notable Examples
- Banking and fintech portals: Enforcing Strict CSP with per-request nonces and violation monitoring.
- Next.js Middleware CSP: Generating unique nonces per SSR request and forwarding them to framework script tags.