Content Security Policy (CSP) is a mechanism by which a website tells the browser, for each page it serves, which sources of content are allowed and which behaviours are forbidden. The server sends the policy as an HTTP response header; the browser reads it before running the page and then blocks covered operations that violate an enforced policy, such as a script injected from an unexpected domain or an inline event handler smuggled into a comment field. The site declares the rules; the browser enforces them.
CSP addresses cross-site scripting, where injected code can execute with the page’s privileges. CSP gives the site a way to describe what its legitimate script looks like, so that many injected scripts can be blocked even when unsafe markup reaches the document. The result depends on the policy’s rules and whether trusted code itself can be misused. It also handles related concerns: preventing a page from being framed by other sites, stopping form submissions to unexpected destinations, and upgrading insecure subresource requests.
Policy Delivery and Directives
The primary delivery channel is the Content-Security-Policy response header, and the recommendation is to send it on every HTML response, not only the main document. A policy can also be embedded in an HTML meta element for static sites that cannot set headers, but the meta route does not support every feature, including framing control and reporting. A CSP header contains semicolon-separated directives. Some constrain resource sources; others control navigation, document embedding or reporting.
Directives map to resource categories. The script source policy, expressed through script-src, governs JavaScript. Others cover stylesheets, images, fonts, media, frames the page embeds, connections made by scripts, workers, and the destinations of form submissions. The default-src directive supplies a fallback for fetch directives that lack a more specific applicable rule. It does not automatically cover directives such as form-action, base-uri or frame-ancestors. Other useful restrictions include frame-ancestors restricts which documents may embed the page, base-uri prevents an injected base element from redirecting relative URLs, object-src set to none disables plugins, and upgrade-insecure-requests rewrites plain HTTP subresource URLs to HTTPS.
Source-list directives accept several expression types. Entries can be the keyword self for the page's own origin, specific hosts with optional wildcards for subdomains, schemes such as https:, the keyword none to block the category entirely, or the nonce and hash expressions described next. Two further keywords, unsafe-inline and unsafe-eval, loosen the policy by re-enabling inline script and string evaluation; both are discouraged because they can significantly weaken script restrictions; their exact effect depends on the other expressions present.
Nonces, Hashes and Source Lists
Early policies relied on host allowlists: permit scripts from the site's own origin plus a handful of trusted CDNs. This approach proved brittle. An allowed domain may host user-controlled content or a JSONP endpoint that attackers can misuse. Current guidance favours a strict policy built from nonces or hashes instead.
A CSP nonce is a random value generated fresh for every response. The server places it in the header, as nonce- followed by the value, and sets the same value in a nonce attribute on each script element it intends to run. In a nonce-based policy, a matching nonce authorises the script. An injected script without that authorisation is blocked unless another policy rule permits it. Security depends on an unpredictable nonce and on trusted rendering code assigning it only to intended scripts. The requirement that the nonce be unique per response means pages must be rendered dynamically or at least have the nonce stamped at serve time; a cached page with a fixed nonce defeats the purpose.
Hashes serve static content. The server computes a SHA-256, SHA-384 or SHA-512 digest of each inline script's exact text and lists the Base64 digest in the policy. Any script whose content matches runs; a single changed character invalidates it. Hashes suit static delivery when the policy is updated alongside script changes; nonces suit dynamically rendered pages. The strict-dynamic keyword complements both: it lets a script that was itself authorised by nonce or hash load further scripts programmatically, which keeps third-party tag loaders working without allowlisting their hosts. The trade-off is that a trusted script that builds script elements from untrusted input becomes a bypass.
Enforcement vs Report-Only Mode
A policy delivered in the Content-Security-Policy header is enforced: violations are blocked. The same policy delivered in Content-Security-Policy-Report-Only is only observed: the browser lets the page behave as it would without the policy, and can send a content security policy report describing a violation to a configured endpoint. Reporting support and delivery vary, so reports are diagnostic evidence rather than a complete audit log. The two headers can be sent together, which allows a site to enforce a lenient policy while trialling a stricter one on live traffic.
A report-only rollout can reveal undocumented fonts, legacy inline handlers and third-party dependencies before enforcement breaks them. Reporting itself has two mechanisms. The newer one uses the report-to directive together with a Reporting-Endpoints header, delivering structured JSON reports; the older report-uri directive is deprecated but still sent alongside for browsers that lack the newer support. Report-only policies cannot be delivered through a meta element. Without a reporting destination, developers may still see console diagnostics, but cannot rely on receiving remote reports.
What CSP Protects Against
The primary target is script injection. A correctly constructed strict CSP can prevent unauthorised script elements, inline handlers and javascript: URLs from executing. String evaluation is also restricted unless separately allowed. These controls can stop an injection from becoming script execution, although they cannot repair every unsafe application flow. The Trusted Types directives extend this to DOM-based injection by requiring suitable typed values at covered sinks such as innerHTML. The application must still implement an effective policy: creating a Trusted Types policy that accepts arbitrary input does not sanitise it automatically.
Clickjacking is addressed by frame-ancestors, which takes precedence over X-Frame-Options when both are enforced by a supporting browser and allows finer control over which origins may embed the page. Data exfiltration is partly constrained by connect-src and form-action, but those directives cover particular channels, not every possible way data could leave a page. Other resource requests, navigation and permitted endpoints need separate consideration. Mixed content is reduced by upgrade-insecure-requests, though that directive does not replace Strict-Transport-Security for top-level navigations.
Limitations and Common Mistakes
CSP is defence in depth. It assumes an injection has already happened and tries to limit the consequences; it does nothing about the injection itself. Output encoding, input validation and safe templating remain necessary, and a site whose only defence is CSP is exposed to any gap in the policy and to browsers that implement it incompletely. CSP also plays no part in authentication or authorisation: it cannot tell who the user is or what they may access.
Policies fail in predictable ways. Allowlists that include a CDN hosting arbitrary user content effectively allow any script. The unsafe-inline keyword, often added to make an old template work, is ignored once a nonce or hash is present but silently neutralises an allowlist policy. Reusing a predictable or disclosed nonce, or stamping it onto injected scripts, defeats the intended nonce boundary. Overly broad default-src values such as https: permit any secure host. Test important page flows before enforcement and investigate reports before relaxing the rules.