Content Security Policy (CSP) Fundamentals
What you'll learn: How CSP acts as a bouncer for JavaScript execution, controlling which sources your browser trusts to run code and blocking the most dangerous XSS attack vectors.
The Core Problem
After learning about the Same-Origin Policy, you know browsers try to isolate content. But what if an attacker sneaks malicious JavaScript into your own pages through XSS? The browser sees it as "same-origin" and executes it. That's where CSP comes in.
What Is CSP?
Content Security Policy is an HTTP response header that tells the browser, "Only execute JavaScript from these approved sources—and block everything else." Think of it as a security guard with an approved vendor list at a building entrance. No credentials? You don't get in.
How CSP Restricts JavaScript
CSP policies define directives that whitelist safe sources:
Content-Security-Policy: script-src 'self' https://trusted-cdn.example.com
This policy says: "Only run scripts from my own origin ('self') or from trusted-cdn.example.com. Block everything else."
Preventing Inline Scripts
The most powerful CSP defense blocks inline scripts entirely—no <script> tags embedded directly in HTML, no onclick="..." handlers. This neutralizes most XSS attacks because injected payloads typically appear inline:
<!-- Blocked by CSP: -->
<script>alert(document.cookie)</script>
<img src=x onerror="alert(1)">
Without CSP, these execute. With script-src 'self', the browser refuses to run them—even if an attacker successfully injects them.
Why It Matters
CSP transforms XSS from automatic code execution into a blocked policy violation. It doesn't prevent injection, but it prevents execution—drastically reducing damage.
Key Takeaway:
CSP restricts JavaScript to approved sources and blocks inline scripts by default, turning most XSS payloads into harmless text that the browser refuses to execute.