// http header · security header

Content-Security-Policy

Restrict where resources may load from

What the Content-Security-Policy header does

Content-Security-Policy (CSP) restricts where the page may load resources from — scripts, styles, images, and more — which is one of the strongest defences against cross-site scripting (XSS). default-src 'self' limits everything to the same origin unless overridden.

Example

Content-Security-Policy: default-src 'self'

Content-Security-Policy in practice

A strict starting policy

Content-Security-Policy: default-src 'self'; img-src 'self' data:; object-src 'none'; frame-ancestors 'none'; base-uri 'self'

Report-only while testing

Content-Security-Policy-Report-Only: default-src 'self'; report-to csp-endpoint

Common Content-Security-Policy questions and problems

Refused to load the script/style because it violates the Content Security Policy directive

The page's policy does not allow that source. Add the specific origin to the right directive (script-src, style-src, img-src), use a nonce or hash for inline code, or remove the offending resource.

How do I roll out CSP safely?

Start with Content-Security-Policy-Report-Only and a report endpoint. Review the violations, adjust the policy, and only then enforce it.

Why avoid 'unsafe-inline'?

It allows any inline script, which defeats most of CSP's protection against cross-site scripting. Use nonces or hashes instead.

What is default-src?

A fallback for fetch directives that are not set explicitly. A strict start is default-src 'self'.

Content-Security-Policy vs related headers

  • X-Frame-Options: X-Frame-Options only controls framing. CSP's frame-ancestors directive does the same and more, and takes precedence in modern browsers.
  • Strict-Transport-Security: HSTS forces HTTPS. CSP restricts what a page may load and run.

Where it's used

Content-Security-Policy is a security header. Security headers tell the browser to turn on protections against common web attacks.

Other security headers