Content-Security-Policy (CSP)

Content-Security-Policy is an HTTP response header that tells the browser exactly which sources of content are permitted on a page. It is the most effective browser-side defense against cross-site scripting (XSS) and data injection attacks.

How CSP Works

When the browser receives a Content-Security-Policy header, it parses the directives and enforces them for every resource the page attempts to load. If a script, stylesheet, image, or other resource does not match the policy, the browser blocks it and logs a violation. The page still loads, but the blocked resource does not execute or render.

CSP operates on an allowlist model. By default, everything is blocked unless explicitly permitted by a directive. If you do not specify a directive for a particular resource type, the browser falls back to default-src.

Key Directives

Example Policies

Basic policy

Content-Security-Policy: default-src 'self'; img-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline'

This allows scripts, fonts, and connections only from the same origin. Images can come from the same origin or cdn.example.com. Inline styles are permitted (not ideal, but sometimes necessary during migration).

Strict policy with nonces

Content-Security-Policy: default-src 'none'; script-src 'nonce-abc123'; style-src 'nonce-abc123'; img-src 'self'; connect-src 'self'; font-src 'self'; base-uri 'none'; form-action 'self'

Nonces are random values generated per-request by the server. Only <script> and <style> tags with a matching nonce attribute will execute. This is the strongest approach because it does not require maintaining a list of trusted domains and blocks all injected scripts regardless of source.

Source values reference

Report-Only Mode

Use the Content-Security-Policy-Report-Only header to test a policy without enforcing it. The browser evaluates the policy and sends violation reports, but does not block any resources. This lets you identify what would break before going live.

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-reports

Deploy in report-only mode first, review the violation reports, adjust the policy, and then switch to the enforcing Content-Security-Policy header.

Common Mistakes

Inspect the Content-Security-Policy and other security headers for any site.

Check CSP headers for your site

Grade your CSP with the security headers tool →