Protection

12 min readUpdated

Content Security Policy (CSP): what it means, directives and header examples

Quick answer

CSP means Content Security Policy, a response header (Content-Security-Policy) that tells the browser which scripts, styles, images, connections and frames a page may use. Anything the policy does not allow is blocked and logged in the console, so a script an attacker injects into the page does not run. It is a second layer of defence against cross-site scripting and, through frame-ancestors, against clickjacking. Roll it out in Report-Only mode first, and allow your own inline code with nonces or hashes rather than 'unsafe-inline'.

01What does CSP mean?

CSP stands for Content Security Policy. A server sends it as the Content-Security-Policy response header, and the browser enforces it for that page: each directive lists the sources one type of content may come from, and everything else is refused. The rules are defined in the W3C's Content Security Policy Level 3 specification, still a Working Draft, which OWASP notes is very widely supported in modern browsers.

Its main job is to contain cross-site scripting (XSS). If an attacker injects a script tag or an onclick attribute into your HTML, a strict policy stops it from running, because the injected code carries neither the page's nonce nor an allowed hash. The same header controls which sites may frame your page (frame-ancestors, the defence against clickjacking), where forms may submit (form-action), which URL a base element may set (base-uri), and whether http:// subresources are loaded over HTTPS (upgrade-insecure-requests).

OWASP says CSP should not be the only defence against XSS, which falls under Injection in the OWASP Top 10: it is a layer on top of correct output encoding. It does nothing against attacks that never run in a browser, such as SQL injection, and form-action does not stop cross-site request forgery, because a forged request is sent from the attacker's page, not yours. Fixing the injection, or filtering it at a web application firewall, is still needed.

02Content-Security-Policy header or meta tag?

The response header is the normal way to deliver a policy and the only one with every feature. A meta element with http-equiv="Content-Security-Policy" also works, and MDN suggests it for single-page apps served as static files, but the specification leaves several features out of it, and a meta policy does not apply to content that comes before the element.

In Chromium, a meta policy containing frame-ancestors logs "The Content Security Policy directive 'frame-ancestors' is ignored when delivered via a <meta> element." while its script-src rule is still enforced.

Policies add up rather than replace each other. A page can receive several CSP headers, a meta policy and a Report-Only header at once, and every request must pass every enforced policy, so an extra policy can only restrict further. A header allowing 'unsafe-inline' next to a second header allowing only 'self' still blocks the inline script, because every policy must allow it. This matters when the application, the web server and a CDN each add a policy.

FeatureHTTP headermeta tag
Fetch directives such as script-src and img-srcYesYes
Nonces and hashesYesYes
frame-ancestors and sandboxYesNo, ignored
Violation reportsYesNo, report-uri is ignored
Report-Only modeYesNot supported
Covers the whole documentYesOnly content after the meta element

03Which CSP directives do you need?

Directives are separated by semicolons, each followed by its allowed sources. default-src is the fallback for the fetch directives, which load content, but not for frame-ancestors, base-uri or form-action. A directive that is missing restricts nothing, so set those three explicitly.

DirectiveControlsFalls back to default-srcTypical value
default-srcEvery fetch directive that is not setNot applicable'self'
script-srcExternal and inline scripts, event handler attributes, eval()Yes'nonce-{RANDOM}' 'strict-dynamic'
style-srcStylesheets, style elements and style attributesYes'self', plus a nonce for inline styles
img-srcImagesYes'self' data:
connect-srcfetch(), XMLHttpRequest, WebSocket, EventSource, sendBeacon()Yes'self' and your API origin
frame-srcPages your page embeds in iframesYes, through child-srcOnly the embeds you use
object-srcobject and embed elements (plugins)Yes'none'
frame-ancestorsWhich sites may embed your pageNo'none', or 'self'
base-uriURLs a base element may setNo'none', or 'self'
form-actionWhere forms on the page may submitNo'self'
upgrade-insecure-requestsLoads http:// subresource URLs over https://NoTakes no value
report-toEndpoint for violation reports, named in Reporting-EndpointsNocsp-endpoint

04Nonces, hashes and why 'unsafe-inline' defeats the point

'unsafe-inline' in script-src lets every inline script run, including an injected one, which is what the policy is meant to stop. Nonces and hashes allow your own inline code without that hole. MDN calls a policy built on them a strict CSP and recommends it against XSS.

A nonce is a random value the server writes into the header as 'nonce-...' and into the nonce attribute of each script tag it trusts. The specification requires a unique value every time a policy is sent, at least 128 bits long and from a cryptographically secure random generator. Such pages cannot be static HTML, and a CDN or page cache that stores them would give every visitor the same nonce, so keep nonce-bearing HTML out of shared caches, or use hashes on pages you cache.

A hash is the base64 SHA-256, SHA-384 or SHA-512 digest of an inline script's exact text, written as 'sha256-...'. It suits static and cached pages, but OWASP notes that any change to the script, even in whitespace, stops it from running, and MDN notes that external scripts also need a matching integrity attribute. Chromium prints the hash of a blocked inline script in the console; copy it only once you know the script is yours.

Two traps. When a directive contains a nonce or a hash, browsers ignore 'unsafe-inline' in it; Chromium logs "Note that 'unsafe-inline' is ignored if either a hash or nonce value is present in the source list." And inline event handlers such as onclick cannot carry a nonce: hashes cover them only with 'unsafe-hashes', which the specification says to avoid on modern sites, so move them into a script file with addEventListener, as OWASP recommends. eval() is blocked too unless you add 'unsafe-eval', which MDN says to avoid.

A nonce in the header and in the page; the value must be new on every response
Content-Security-Policy: script-src 'nonce-q8bB3kV1yLx0m4Rr6Zp2Cw==' 'strict-dynamic'; object-src 'none'; base-uri 'none'

<script nonce="q8bB3kV1yLx0m4Rr6Zp2Cw==">
  // runs: the nonce matches the header
</script>
<script>
  // blocked: no nonce, which is what an injected script looks like
</script>

05What does 'strict-dynamic' do?

'strict-dynamic' passes the trust of a nonce or hash on to scripts that a trusted script loads itself, such as a tag manager adding script elements, so those scripts need no nonce or allowlist entry of their own.

It also switches allowlists off: browsers ignore host and scheme sources, 'self' and 'unsafe-inline' in that directive, so every script tag in the HTML needs the nonce, even for your own files. The specification advises auditing code that creates scripts through DOM APIs, since a trusted script that inserts a URL taken from user input would load it.

With strict-dynamic, a nonced script that adds a script from another origin runs it, while a script tag in the HTML pointing to that origin and an inline script without the nonce are both blocked. OWASP's strict template is script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; or the same with a 'sha256-...' hash instead of the nonce.

06Report-Only mode and CSP violation reports

The Content-Security-Policy-Report-Only header takes the same syntax but blocks nothing: the browser logs each violation and sends a report if the policy names an endpoint. Use it to test a policy on real traffic, or to trial a stricter revision beside an enforced one. Both headers can be sent together; a meta tag cannot carry Report-Only.

report-uri takes a URL and posts JSON as application/csp-report; CSP Level 3 deprecates it and says it is ignored when report-to is present. report-to names an endpoint from a separate Reporting-Endpoints header, and its reports arrive as application/reports+json. MDN lists report-to as Baseline newly available only since March 2026, so send both.

Chromium posts report-uri reports shortly after the page loads. It named the effective directive, the blocked URI (inline, for an inline script) and the disposition (report). Group reports by those fields and allow only sources you recognise.

Report-Only with both reporting directives, and an example report-uri body (trimmed)
Reporting-Endpoints: csp-endpoint="https://example.com/csp-reports"
Content-Security-Policy-Report-Only: default-src 'self'; script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; report-to csp-endpoint; report-uri https://example.com/csp-reports

POST /csp-reports   Content-Type: application/csp-report
{"csp-report":{"document-uri":"http://127.0.0.1:18091/inline.html","violated-directive":"script-src-elem",
 "effective-directive":"script-src-elem","disposition":"report","blocked-uri":"inline","line-number":1,"status-code":200}}

07How to roll out a CSP without breaking your site

Enforcing a policy written in one go usually breaks a login, a payment widget or analytics. This order avoids that.

  • List what your pages load: the Network panel shows the origins of scripts, styles, images, fonts, frames and connections, including widgets and tag managers
  • Send a Report-Only policy with an endpoint: the strict template for server-rendered pages, an allowlist based on 'self' for static files
  • Collect reports across every template, including sign-in, checkout and admin pages
  • Change the code rather than widening the policy: move inline handlers into script files, add the nonce to your script tags, hash static inline blocks
  • Allow a third party only in the directive that needs it, such as img-src for a pixel or connect-src for beacons, not in default-src
  • Enforce by renaming the header to Content-Security-Policy, keep reporting on, and trial the next revision in a Report-Only header beside it

08Content-Security-Policy header examples

Replace example.com, add the sources your pages really use, and run each policy in Report-Only mode first.

The static-site policy is an allowlist built on 'self' and needs no server code. OWASP calls this kind of policy basic and non-strict: it blocks inline and third-party scripts but trusts every file on your origin, and OWASP warns that permissive allowlists are likely to lead to bypasses. For a few inline scripts, add their hashes to a script-src directive rather than 'unsafe-inline'.

The single-page app policy uses a nonce, so the script tag of your own bundle needs it too. connect-src lists the WebSocket address explicitly, because MDN notes that 'self' does not resolve to WebSocket schemes in all browsers. If your framework injects style elements at runtime, check whether it accepts a nonce before adding 'unsafe-inline' to style-src.

Two starting policies (wrapped for reading; send each as one header line)
# 1. Static site, everything served from your own origin
Content-Security-Policy: default-src 'self'; img-src 'self' data:; object-src 'none';
  base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests

# 2. Single-page app with a separate API, HTML rendered per request
Content-Security-Policy: default-src 'self'; script-src 'nonce-{RANDOM}' 'strict-dynamic';
  style-src 'self'; img-src 'self' data:;
  connect-src 'self' https://api.example.com wss://api.example.com;
  object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'

09CSP example for a site with Google Analytics

Third-party tools need sources in several directives. For Google Analytics without Ads features, Google's CSP guide for Tag Manager lists https://www.googletagmanager.com for scripts, the same host plus https://*.google-analytics.com for images, and both plus https://*.google.com for connections. Ads features need more hosts, with each Google top-level domain listed separately.

Google recommends a nonce for the inline tag snippet. A stricter variant replaces the host and 'self' in script-src with 'strict-dynamic' and puts the nonce on every script tag; img-src and connect-src still need the hosts, because 'strict-dynamic' only concerns scripts. Vendors change their hosts, so keep reporting on after you enforce.

Allowlist policy for Google Analytics through Google Tag Manager, after Google's CSP guide (wrapped for reading)
Content-Security-Policy: default-src 'self';
  script-src 'self' 'nonce-{RANDOM}' https://www.googletagmanager.com;
  img-src 'self' https://www.googletagmanager.com https://*.google-analytics.com;
  connect-src 'self' https://www.googletagmanager.com https://*.google-analytics.com https://*.google.com;
  object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'

<script nonce="{RANDOM}">/* Google Tag Manager snippet */</script>

10How to set CSP in nginx, Apache and Express

nginx: use add_header with always, so error pages carry the policy too; with always, both headers below are sent on 200 and 404 responses. A location with its own add_header drops the server-level ones, which the security headers guide solves with an include file.

Apache httpd: use Header always set from mod_headers. The documentation says always also covers error responses and internal redirects, and that add can create two headers with the same name, which for CSP means two policies. In .htaccess the directive needs AllowOverride FileInfo.

Express: create the nonce in a middleware, set the header, and keep the value in res.locals for the templates. Nonce policies belong in the application, the only place that can put the same fresh value into the header and the page. With Express 5.2.1 on Node.js 22, the nonced script ran and a script without the nonce was blocked.

A reverse proxy or CDN can add a fixed policy, such as frame-ancestors and object-src, for an application that sends none, a form of virtual patching. It is enforced together with any policy the application sends.

nginx, Express and Apache examples; the Apache line follows the mod_headers documentation
# nginx, server block: an enforced policy plus a stricter trial policy
add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" always;
add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; report-uri /csp-reports" always;
location = /csp-reports {
    proxy_pass http://127.0.0.1:9000;   # your report collector
}

# Apache httpd, virtual host or .htaccess (mod_headers loaded)
Header always set Content-Security-Policy "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests"

// Express: a fresh nonce for every response
const crypto = require("node:crypto");
const express = require("express");
const app = express();

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString("base64");   // 128 bits
  res.locals.cspNonce = nonce;
  res.set(
    "Content-Security-Policy",
    `script-src 'nonce-${nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'`
  );
  next();
});

app.get("/", (req, res) => {
  res.type("html").send(`<!doctype html><title>Home</title>
<script nonce="${res.locals.cspNonce}">console.log("allowed");</script>`);
});

app.listen(3000);

11"Refused to load the script": fixing CSP errors in the console

Every block is logged in the browser console with the directive that caused it. Older Chrome versions start the message with "Refused to", the wording most search results quote; current Chromium says "Loading the script ... violates the following Content Security Policy directive" and ends with "The action has been blocked." Firefox writes "The page’s settings blocked ...". A message ending in "The policy is report-only" blocked nothing.

Read the directive, not only the URL: if the message says that 'script-src-elem' or 'connect-src' was not explicitly set, change the fallback directive it names. And check that you recognise the blocked source; an unknown script is exactly what the policy is there to stop.

Message starts withCauseFix
Refused to load the script, or Loading the scriptExternal script from a source the policy does not listAdd its origin to script-src, or give the tag the nonce with 'strict-dynamic'
Refused to execute inline script, or Executing inline scriptScript block without a valid nonce or hashAdd the nonce, or the hash once you know the code is yours
Executing inline event handleronclick, onload or a similar attributeMove it into a script file and use addEventListener
Applying inline styleStyle block or style attribute without a nonce or hashMove it into a stylesheet, or give the style element the nonce
Connecting tofetch, XMLHttpRequest, WebSocket or a beacon to an origin not in connect-srcAdd that origin to connect-src
Framing ... frame-ancestorsThe framed page does not allow being embeddedOnly the framed site can change it
Framing ... frame-src or default-srcYour own policy does not allow that embedAdd the origin to frame-src
Evaluating a string as JavaScripteval() or a similar API without 'unsafe-eval'Remove the eval call
The Content Security Policy directive 'frame-ancestors' is ignored when delivered via a <meta> elementframe-ancestors in a meta tagSend it as a response header
Chromium 151 messages from testing (test URLs replaced with cdn.example.net, hashes shortened), then the older Chrome wording from the Chromium 120 source and the Firefox wording from Firefox's source
# Chromium 151
Loading the script 'https://cdn.example.net/x.js' violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. The action has been blocked.
Executing inline script violates the following Content Security Policy directive 'script-src 'self''. Either the 'unsafe-inline' keyword, a hash ('sha256-nWx8...'), or a nonce ('nonce-...') is required to enable inline execution. The action has been blocked.

# Older Chrome versions
Refused to load the script 'https://cdn.example.net/x.js' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

# Firefox
The page’s settings blocked the loading of a resource (script-src-elem) at https://cdn.example.net/x.js because it violates the following directive: “script-src 'self'”

12How to disable Content-Security-Policy, and why not on your site

The policy is enforced by each visitor's browser. Switching it off in your own browser only changes what you see while testing: every other visitor still gets the policy, and nothing on the site is fixed.

Firefox removed its about:config switch, security.csp.enable, in Firefox 99; in that bug Mozilla's engineers recommended a WebExtension that overrides the CSP header, or a proxy such as ZAP or Burp Suite, for local development. Test automation has options such as Playwright's bypassCSP. An extension that strips CSP headers can remove the protection from every site you open, so keep it in a separate browser profile.

On the site itself, deleting the header is the wrong fix for a broken page. It removes the XSS safety net and the clickjacking protection for every visitor, and the code that tripped the policy is still there. If a policy breaks production, send it as Content-Security-Policy-Report-Only while you fix the cause, then enforce it again.

If you cannot find where a policy comes from, check every layer that can add one: the application or CMS and its security plugins, the web server, a CDN or proxy in front, and meta elements in the HTML.

Questions

Frequently asked questions

01Is CSP enough to prevent XSS?
No. OWASP says CSP should not be relied on as the only defence against cross-site scripting. Encode output correctly for its context first; a strict policy is the second layer that stops injected code from running when that fails. A policy with long allowlists or 'unsafe-inline' protects far less than one based on nonces or hashes.
02Should I use a nonce or a hash?
Use a nonce when the server renders each page, because it can write a fresh random value into the header and every script tag. Use hashes when the HTML is static or cached, because a hash stays valid as long as the script text does not change. Both work with 'strict-dynamic'.
03Does a CSP meta tag protect against clickjacking?
No. frame-ancestors is ignored when the policy is delivered in a meta element, and Chromium logs a console message saying so. Send frame-ancestors in a Content-Security-Policy response header, from the application, the web server, a reverse proxy or a CDN.
04Is report-uri deprecated?
Yes. CSP Level 3 deprecates report-uri in favour of report-to and tells browsers to ignore report-uri when report-to is present. MDN lists report-to as newly available across current browsers only since March 2026, so send both for now: browsers that understand report-to use it, older ones fall back to report-uri.
05How do I disable Content-Security-Policy for testing?
Only in your own browser: use an extension that rewrites response headers, an intercepting proxy, or an automation option such as Playwright's bypassCSP. Firefox removed its about:config switch in version 99. None of this affects other visitors; to unblock them, fix the policy or the code it blocks.

Sources

Sources and verification

The configuration and commands on this page are examples, not a tested recipe. Adapt them to your system and check them before use (nginx -t for nginx, apachectl configtest for Apache).

  1. 01Content Security Policy Level 3 (W3C Working Draft) · W3C
  2. 02Content-Security-Policy header reference · MDN
  3. 03Content Security Policy (CSP) guide: strict CSP, nonces, hashes, reporting · MDN
  4. 04CSP: report-to · MDN
  5. 05CSP: report-uri · MDN
  6. 06CSP: connect-src · MDN
  7. 07Content Security Policy Cheat Sheet · OWASP
  8. 08csp_directive_list.cc (Chromium 120): older console messages · Chromium
  9. 09csp_directive_list.cc (main): current console messages · Chromium
  10. 10csp.properties: Firefox CSP console strings · Mozilla
  11. 11Bug 1754301: Consider removing security.csp.enable pref · Mozilla Bugzilla
  12. 12Browser.newContext: bypassCSP option · Playwright
  13. 13Use a Content Security Policy with Google Tag Manager · Google for Developers
  14. 14Module ngx_http_headers_module: add_header · nginx.org
  15. 15Apache Module mod_headers: Header directive · Apache HTTP Server Project
  16. 16Express 5.x API: res.set() and res.locals · Express

Last updated