What Is a Content Security Policy (CSP)?

Data Security Knowledge Base 

Content Security Policy (CSP) Definition

Text

A content security policy (CSP) is a browser security standard that lets a website control which resources — scripts, styles, images, fonts, and frames, a browser is allowed to load and execute on a page. It's delivered as an HTTP response header made up of rules called directives, and its main purpose is defending against cross-site scripting (XSS) and other code injection attacks.

CSP works on a default-deny principle: anything not explicitly permitted by the policy is blocked by the browser. Beyond XSS, it also protects against clickjacking and helps ensure resources load over HTTPS. Now a W3C standard, it's supported by all modern browsers.

What are CSP directives?

Text

CSP directives are the individual rules that make up a policy, each controlling a specific resource type. They're written in the header separated by semicolons, for example: Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com. The most important is default-src, which acts as a fallback for any directive you don't explicitly set. script-src controls where JavaScript can load from and is your main XSS defense. style-src, img-src, font-src, and connect-src govern stylesheets, images, fonts, and API calls. frame-ancestors controls which sites can embed your page in an iframe for clickjacking protection, while object-src 'none' blocks legacy plugins.

How does a content security policy prevent XSS attacks?

Text

CSP prevents XSS by controlling script execution at the browser level, so injected code simply doesn't run. It works three ways. First, it restricts script sources to an approved allowlist — if an attacker injects a script from a malicious domain, the browser blocks the request. Second, it blocks inline scripts, including <script> tags and event handlers like onclick or onerror, which is how most XSS payloads are delivered. Third, it disables dynamic code execution functions like eval(). The key benefit is defense in depth: even if input sanitization fails and an attacker successfully injects a payload, CSP stops it from executing.

How do you implement a content security policy?

Text

A CSP is implemented by setting the Content-Security-Policy HTTP response header on every response from your server, not just the main document. The recommended approach is to start in Report-Only mode using the Content-Security-Policy-Report-Only header — this logs violations without blocking anything, letting you find what would break before enforcing. From there, begin with a restrictive baseline like default-src 'self' and open up only what you need. Best practice is a strict, nonce-based policy: generate a unique cryptographic nonce per request and allow only scripts carrying it, rather than maintaining a fragile domain allowlist. Avoid 'unsafe-inline' and 'unsafe-eval', which undermine the protection.