Content-Security-Policy
Response header Security

Overview

Content-Security-Policy (CSP) is a security header that finely controls, via directives, which sources of scripts, styles, images, frames, and more the browser may load or execute on a page. By blocking untrusted resources it strongly mitigates XSS, data exfiltration, and clickjacking.

A policy is built from directives like default-src and script-src, each with a list of allowed sources.

Details

Its most powerful effect is using script-src to block inline scripts and arbitrary-domain scripts. To stop XSS-injected <script> from running, avoid unsafe-inline and instead have the server issue a random nonce per response, attaching nonce="..." only to scripts it emits (script-src 'nonce-...'), or use script hashes ('sha256-...'). Adding 'strict-dynamic' propagates trust from a trusted script to the scripts it loads, reducing the burden of maintaining a domain allowlist.

The frame-ancestors directive controls who may frame this page in an iframe — the modern, superior replacement for X-Frame-Options against clickjacking. Use frame-ancestors 'none' or 'self' to block external framing.

Enforcing a policy straight in production can break legitimate resources, so a safe rollout is to first collect violations via the Content-Security-Policy-Report-Only header (reporting to report-to/report-uri), review them, then promote to an enforcing CSP.

Syntax

Content-Security-Policy: <directive> <source-list>[; <directive> <source-list>]*

e.g. Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; object-src 'none'; frame-ancestors 'none'

Directives / values

default-srcFallback source policy applied when a more specific -src directive is absent.
script-srcAllowed sources for loading/executing scripts — the core of XSS defense.
style-srcAllowed sources for stylesheets and inline styles.
img-src / connect-src / font-srcAllowed sources for images, fetch/XHR/WebSocket, and fonts.
frame-ancestorsWhich origins may frame this page — the modern replacement for X-Frame-Options.
'nonce-<base64>' / 'sha256-<hash>'Allow specific inline scripts via a nonce or hash (avoiding unsafe-inline).
'strict-dynamic'Propagates trust from a nonce-trusted script to scripts it loads.
report-to / report-uriEndpoint to which policy-violation reports are sent.

Notes

Related headers

Content-Security-Policy-Report-OnlyX-Frame-OptionsX-Content-Type-OptionsReferrer-Policy

Related status codes

Specification