Security

Content Security Policy (CSP) Explained, With Real Browser Errors

A Content Security Policy (CSP) is an HTTP response header that tells the browser which scripts, styles, images and connections a page is allowed to load, and blocks everything else. Its main job is to stop injected JavaScript from running, which turns many cross-site scripting (XSS) bugs from an account takeover into a blocked request and a console error.

A minimal policy looks like this:

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

How CSP works

The server sends the header with the page. The browser then checks every resource the page tries to use against the policy before loading or running it. A script from a domain that isn't listed, an inline <script> without the right nonce, a call to eval(), a fetch() to an unlisted API: each is blocked and reported in the developer console.

MDN describes the primary use case as controlling which resources, especially JavaScript, a document can load, as a defence against XSS. The same header can also block clickjacking (frame-ancestors) and upgrade HTTP requests to HTTPS (upgrade-insecure-requests). If you're new to the attack CSP defends against, XSS explained covers it first.

The directives you'll actually use

DirectiveControlsTypical value
default-srcFallback for every fetch directive you don't set'self'
script-srcJavaScript: files, inline scripts, eval, inline event handlers'nonce-…' 'strict-dynamic' or 'self'
style-srcStylesheets, <style> blocks, style="" attributes'self'
img-srcImages and favicons'self' data:
connect-srcfetch, XHR, WebSocket, EventSource'self' https://api.example.com
object-src<object> and <embed>'none'
base-uriWhat a <base> tag may point to'none' or 'self'
frame-ancestorsWho may embed this page in an iframe'none'
form-actionWhere forms may submit'self'

Source values are either keywords in single quotes ('self', 'none', 'unsafe-inline', 'unsafe-eval', 'strict-dynamic'), schemes (https:, data:), hosts (https://cdn.example.net), or a nonce or hash. The quotes around keywords are required: self without quotes means a host called "self".

What a CSP violation looks like in the console

To get exact messages, we served a test page from a local Node.js server with this header and loaded it in headless Chrome 156:

Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-r4nd0m'; img-src 'self'; connect-src 'self'

Each blocked action produced one console error. These are verbatim:

What the page didChrome's error (shortened where marked …)
Inline <script> without a nonceExecuting inline script violates the following Content Security Policy directive 'script-src 'self' 'nonce-r4nd0m''. Either the 'unsafe-inline' keyword, a hash ('sha256-HF4wl1yWwnXjPpurgVg1o4R9iT5K0XuxG8Hiibtc6Fo='), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.
Script from another domainLoading the script 'https://cdn.example.net/lib.js' violates the following Content Security Policy directive: "script-src 'self' 'nonce-r4nd0m'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked.
eval("1+1")Evaluating a string as JavaScript violates the following Content Security Policy directive because 'unsafe-eval' is not an allowed source of script: …
onclick="…" attributeExecuting inline event handler violates the following Content Security Policy directive …
fetch() to another domainConnecting to 'https://api.example.com/x' violates the following Content Security Policy directive: "connect-src 'self'". The action has been blocked.
style="color:red"Applying inline style violates the following Content Security Policy directive 'default-src 'self''. … Note also that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.

Two details are useful when you fix these. The message names the directive that blocked the resource, including when it fell back to default-src. And for inline code, Chrome prints the exact hash that would allow it. That hash is the base64 SHA-256 of the script's text, which you can reproduce with printf '%s' 'console.log("inline ran")' | openssl dgst -sha256 -binary | base64.

The fetch() failure also surfaces in your JavaScript as a rejected promise with the message Failed to fetch, which looks identical to a network or CORS problem. If a request fails without reaching the server, check the console for a CSP line before debugging CORS. (The CORS error guide covers the other case.)

Allowing your own inline scripts: nonces and hashes

Allowing 'unsafe-inline' in script-src gives up most of the XSS protection, because an injected <script> is inline too. There are two safer ways to allow specific inline scripts.

Nonce

Generate a fresh random value for every response, put it in the header and on each script tag you write:

Content-Security-Policy: script-src 'nonce-q7Rz2bXk9pL0aVn3cT5wYg' 'strict-dynamic'; object-src 'none'; base-uri 'none'

<script nonce="q7Rz2bXk9pL0aVn3cT5wYg">initApp();</script>

In the test above, the script carrying nonce="r4nd0m" ran and the one without it was blocked. MDN says the nonce must be different for every HTTP response and must not be predictable; a fixed nonce like our test value is only acceptable in a test. OWASP adds that you need a real templating engine for nonces, and warns against middleware that stamps a nonce onto every script tag, because injected scripts would receive one too. Generate the value from a cryptographic source, as covered in Math.random vs crypto.getRandomValues.

Hash

For a static inline script that never changes, list its SHA-256 instead: script-src 'sha256-HF4wl1yWwnXjPpurgVg1o4R9iT5K0XuxG8Hiibtc6Fo='. Change one character of the script and the hash no longer matches. Hashes suit static sites, which can't generate a nonce per response.

'strict-dynamic'

With 'strict-dynamic', a script you trusted by nonce or hash may load further scripts, and those are trusted too. That makes tag managers and loaders workable without listing every domain. MDN notes the trade-off: if a trusted script builds <script> elements from attacker-controlled input, CSP won't protect you.

Inline event handlers (onclick="…") and style="" attributes are a separate problem: Chrome's message notes that hashes don't apply to them unless 'unsafe-hashes' is present. Moving handlers into script files with addEventListener is the clean fix.

Two policies to start from

OWASP's basic policy, for a site that loads everything from its own origin and has no inline scripts:

Content-Security-Policy: default-src 'self'; frame-ancestors 'self'; form-action 'self';

The strict, nonce-based policy that MDN and OWASP both recommend for XSS protection:

Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none';

The strict policy only governs scripts and plugins. Add frame-ancestors 'none' unless your page needs to be embedded; MDN calls it a more flexible replacement for the X-Frame-Options header.

Roll it out with Content-Security-Policy-Report-Only

A new policy almost always breaks something: an analytics snippet, a font from a CDN, an inline style in a template. Ship it first as report-only:

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' 'nonce-r4nd0m'

Nothing is blocked; violations are only logged. In the same Chrome test, every error above turned into an info message ending in The policy is report-only, so the violation has been logged but no further action has been taken., and the inline script and eval both ran.

To collect violations from real users rather than your own console, add a reporting endpoint. MDN recommends the Reporting API: declare an endpoint in a Reporting-Endpoints header and name it in the report-to directive. The older report-uri directive is deprecated, but MDN advises sending both until every browser supports report-to. Run report-only for long enough to see your real traffic, fix or allow each legitimate violation, then switch the header name to Content-Security-Policy.

Setting the header (and the meta tag fallback)

In nginx:

add_header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'" always;

Without always, nginx adds the header only to a list of success and redirect status codes, so your 404 and 500 pages would go out without it. Also note nginx's inheritance rule: add_header directives are inherited from the outer block only if the current block has none of its own, so one add_header inside a location silently drops the server-level CSP for that location.

If you can't set headers, a meta tag in <head> works for most directives:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

The CSP specification excludes frame-ancestors, report-uri and sandbox from meta policies, and doesn't allow report-only mode there. Chrome says so in the console: The Content Security Policy directive 'frame-ancestors' is ignored when delivered via a <meta> element.

Common mistakes

  • Sending two policies and expecting them to merge. Browsers enforce every policy they receive, so a resource must pass all of them. In our test, one header allowing https://images.example.org and a second header with img-src 'self' blocked the image.
  • Forgetting the fallback. Setting only default-src 'self' also blocks data: images, Google Fonts and every inline style, because each unset directive falls back to it.
  • Allowing whole CDNs. script-src https://cdn.jsdelivr.net allows every file that CDN serves, not only the library you meant, so any script an attacker can get onto that CDN passes your policy. Prefer nonces or hashes.
  • Treating CSP as the fix. OWASP calls it a second layer: it doesn't remove the injection bug, so you still need output encoding and input validation.

Frequently asked questions

Does a Content Security Policy prevent XSS?
It limits the damage. CSP stops the browser from running scripts the policy doesn't allow, so an injected script tag or inline handler is blocked. OWASP describes it as a second layer of protection that should not be the only defence against XSS: you still need to encode output and validate input, because CSP doesn't remove the vulnerability from your code.
Should I put CSP in a meta tag or an HTTP header?
Use the Content-Security-Policy HTTP header when you can. A meta tag works for most directives, but the CSP specification excludes frame-ancestors, report-uri and sandbox from meta policies, and a Report-Only policy cannot be set in a meta tag at all. The meta tag is a fallback for static hosting where you can't set headers.
What happens if a page has two Content-Security-Policy headers?
The browser enforces both, so a resource has to be allowed by every policy. Adding a second policy can only make things stricter. In a test with Chrome 156, one header allowing images from a CDN and a second allowing only 'self' resulted in the CDN image being blocked.
Is 'unsafe-inline' always bad?
In script-src it removes most of CSP's protection against XSS, because injected inline scripts are exactly what an attacker adds. In style-src the risk is lower and many sites accept it while they migrate. If a nonce or hash is also present in script-src, the browser ignores 'unsafe-inline' there; Chrome 156 says so in its console error: 'unsafe-inline' is ignored if either a hash or nonce value is present in the source list.

Sources