Dev tools
Content Security Policy (CSP): A Practical Guide
Content Security Policy explained: directives, a CSP header example, nonces and hashes, strict CSP, frame-ancestors, CSP vs CORS, and safe rollout steps.
Content Security Policy (CSP) is a security standard that lets a website tell the browser which scripts, styles, images, frames and connections it's allowed to load and run. You send it as a Content-Security-Policy HTTP response header, and the browser blocks anything the policy doesn't allow. Its main job is limiting the damage of cross-site scripting (XSS): even if an attacker injects a script into your page, a strict policy stops it from executing. The most effective approach today is a "strict CSP" based on nonces or hashes, rolled out in report-only mode first.
This guide explains how content security policy works, gives a CSP header example with every directive explained, shows a CSP nonce example and hash-based policies, covers frame-ancestors for clickjacking, compares content security policy vs CORS, shares real adoption data, and walks through deploying CSP without breaking your site.
What Is Content Security Policy?
CSP is a W3C standard (Level 2 is a Recommendation; Level 3 is a Working Draft that browsers largely implement). It works as an allowlist: the site declares the sources of content it trusts, and the browser enforces that list for every resource on the page.
Without CSP, the browser executes any script that ends up in a page, whether it came from your code, a compromised third-party library or an attacker's injected <script> tag. With CSP, an injected script that isn't on the allowlist (or doesn't carry the right nonce) simply doesn't run.
The W3C specification describes CSP as a defence-in-depth mechanism, not the first line of defence. You still need to escape output, sanitise HTML and validate input; CSP is the safety net when one of those fails. It also helps with other problems: blocking mixed content, limiting where forms can submit, and preventing your site from being framed by attackers.
How CSP Works
- Your server adds a
Content-Security-Policyheader to HTML responses. - The browser parses the policy's directives (rules for each type of resource).
- For every script, style, image, font, frame, fetch request and so on, the browser checks the source against the matching directive.
- Anything not allowed is blocked, and the browser logs a violation in the console and, if configured, sends a report to your reporting endpoint.
There's also a report-only mode: the Content-Security-Policy-Report-Only header applies the same rules but only reports violations instead of blocking. It's how you test a policy on real traffic before enforcing it.
A policy can also be set with a <meta http-equiv="Content-Security-Policy"> tag, but some directives, including frame-ancestors, reporting directives and sandbox, don't work in meta tags. The header is the better option.
CSP Header Example
Here's a CSP header example for a typical site that serves its own scripts and styles, uses one analytics domain and loads images from a CDN:
Content-Security-Policy:
default-src 'self';
script-src 'self' https://analytics.example.com;
style-src 'self';
img-src 'self' https://cdn.example.com data:;
connect-src 'self' https://api.example.com;
font-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'none';
upgrade-insecure-requests(Line breaks are for readability; a real header is a single line, with directives separated by semicolons.)
Reading it line by line: everything defaults to the site's own origin; scripts may also come from the analytics domain; images may come from the CDN or be inline data: URLs; API calls may go to the API domain; plugins are banned entirely; the <base> tag and form submissions are restricted to the site; no other site may frame these pages; and any http:// subresource URLs are upgraded to https://.
This is an allowlist-based policy. It's far better than nothing, but as the next sections explain, it's weaker against XSS than a nonce-based strict policy.
CSP Directives Reference
| Directive | Controls | Typical value |
|---|---|---|
default-src | Fallback for most fetch directives not set explicitly | 'self' |
script-src | JavaScript sources, inline scripts, eval | 'nonce-…' 'strict-dynamic' or 'self' plus domains |
style-src | Stylesheets and inline styles | 'self' (plus nonces or hashes for inline styles) |
img-src | Images and favicons | 'self' plus CDN, often data: |
connect-src | fetch, XHR, WebSocket and EventSource targets | 'self' plus API domains |
font-src | Web fonts | 'self' plus font CDN |
frame-src | Pages your page may embed in iframes | Video or payment provider domains |
frame-ancestors | Which sites may embed your page | 'none' or 'self' |
object-src | <object> and <embed> plugins | 'none' |
base-uri | URLs allowed in <base> | 'self' or 'none' |
form-action | Where forms may submit | 'self' |
worker-src | Web workers and service workers | 'self' |
media-src | Audio and video | 'self' plus media hosts |
upgrade-insecure-requests | Rewrites http:// subresources to https:// | No value |
require-trusted-types-for | Enforces Trusted Types for DOM sinks | 'script' |
report-to | Reporting endpoint group for violations | A group name defined in Reporting-Endpoints |
Directives you don't set fall back to default-src, except for a few such as frame-ancestors, base-uri and form-action, which have no fallback and must be set explicitly.
Source expressions you'll use most:
'self': the page's own origin (scheme, host and port).'none': nothing at all.https://cdn.example.com: a specific host; wildcards such ashttps://*.example.comare allowed.'nonce-abc123': a script or style carrying a matchingnonceattribute.'sha256-…': an inline script or style whose hash matches.'strict-dynamic': scripts loaded by an already-trusted script are trusted too; host allowlists are ignored.'unsafe-inline'and'unsafe-eval': allow inline code andeval; they largely defeat CSP's XSS protection.
Why Allowlists Aren't Enough: Strict CSP
In 2016, Google security researchers (Weichselbaum, Spagnuolo, Lekies and Janc) published "CSP Is Dead, Long Live CSP!", analysing 26,011 unique policies seen across about 1.68 million hosts. They found that 94.72% of distinct policies could be trivially bypassed, and that 14 of the 15 domains most commonly allowlisted for scripts hosted endpoints (such as JSONP callbacks or old library versions) an attacker could abuse to run code. If you allowlist a big CDN, you allowlist every script on it.
Their answer was the strict CSP: instead of listing domains, mark the scripts you trust with a per-response random nonce (or a hash), and use 'strict-dynamic' so those trusted scripts can load their own dependencies. Google's web.dev guidance recommends this form:
Content-Security-Policy:
script-src 'nonce-{RANDOM}' 'strict-dynamic';
object-src 'none';
base-uri 'none';An injected script tag won't have the nonce, so it won't run, even if it points to an allowlisted domain.
CSP Nonce Example
A nonce must be random, unguessable and different for every response. Here's a CSP nonce example in a Node.js Express app:
const crypto = require("crypto");
app.use((req, res, next) => {
res.locals.nonce = crypto.randomBytes(16).toString("base64"); // new nonce per response
res.setHeader(
"Content-Security-Policy",
`script-src 'nonce-${res.locals.nonce}' 'strict-dynamic'; object-src 'none'; base-uri 'none'`
);
next();
});Then every legitimate script tag in your template carries the same nonce:
<script nonce="{{ nonce }}" src="/static/app.js"></script>
<script nonce="{{ nonce }}">
window.appConfig = { theme: "dark" };
</script>Rules that keep nonces safe:
- Generate a new nonce for every HTML response, using a cryptographically secure random generator.
- Never reuse nonces or cache HTML pages that contain them across users.
- Don't echo user input into script tags; a nonce doesn't help if an attacker controls the contents of a trusted script.
- Inline event handlers such as
onclick="..."andjavascript:URLs won't run under a strict policy; move them into scripts withaddEventListener.
Hashes for static pages: if your HTML is static and cached, nonces don't fit. Instead, compute a SHA-256 hash of each inline script's exact contents and list it, for example script-src 'sha256-B2yPHKaXnvFWtRChIbabYmUBFZdVfKKXHbWtWidDVF8=' 'strict-dynamic'. Any change to the script, even whitespace, changes the hash. MDN's guidance sums it up: use nonces if you generate pages dynamically, hashes if you serve static content.
Content Security Policy Frame Ancestors
The content security policy frame ancestors directive controls which sites may embed your pages in <frame>, <iframe>, <object> or <embed>. It's the modern defence against clickjacking, where an attacker loads your page invisibly inside theirs and tricks users into clicking buttons.
frame-ancestors 'none'blocks all framing; the right choice for most apps, login pages and admin panels.frame-ancestors 'self'allows framing only by your own origin.frame-ancestors 'self' https://partner.example.comallows specific partners.
frame-ancestors supersedes the older X-Frame-Options header and is more flexible (it supports multiple origins). Many sites send both for older browsers. It must be sent as an HTTP header; it's ignored in a meta tag.
Content Security Policy vs CORS
Content security policy vs CORS is a common mix-up, because both involve allowed origins. They protect different parties.
| Content Security Policy | CORS | |
|---|---|---|
| Set by | The site serving the page | The server receiving a cross-origin request |
| Protects | Your page's users from injected or unwanted content | Your server's responses from being read by other sites' scripts |
| Question it answers | "What may this page load and run?" | "May a script from another origin read this response?" |
| Main header | Content-Security-Policy | Access-Control-Allow-Origin and related headers |
| Enforced by | The browser, on the page | The browser, on cross-origin requests |
| Typical failure | Your own page's scripts or styles get blocked | Your front end can't read your API's responses |
A site often needs both: CSP on its HTML pages, and CORS on its API so its own front end on another subdomain can call it. Note that connect-src in your CSP must also allow the API's origin, or the browser blocks the request before CORS is even consulted.
How Widely Is CSP Used?
HTTP Archive's Web Almanac 2025 measured CSP across millions of pages:
| Measure (Web Almanac 2025, security chapter) | Value |
|---|---|
Pages sending a Content-Security-Policy header | 21.9%, up from 18.5% in 2024 |
Policies with script-src using 'unsafe-inline' | About 92% |
Policies using 'unsafe-eval' | About 77% |
| Sites using nonces | About 20% |
Sites using 'strict-dynamic' | About 10% |
The almanac notes that 'unsafe-inline' isn't always harmful, because browsers ignore it when a nonce and 'strict-dynamic' are present (a common fallback for very old browsers). Still, the numbers show that most deployed policies don't stop XSS, which is the main reason to have one.
How to Deploy CSP Without Breaking Your Site
- Inventory your scripts. List first-party scripts, inline scripts, inline event handlers and every third party: analytics, tag managers, chat widgets, payment forms, video embeds.
- Choose your approach. Nonce-based strict CSP if you render HTML dynamically; hash-based if it's static. Use an allowlist policy only as a stepping stone.
- Refactor inline code. Move inline event handlers and
javascript:links into script files, and add nonces to legitimate inline scripts. - Set up reporting. Define an endpoint with the
Reporting-Endpointsheader and reference it withreport-to(keepreport-uritoo for older browsers). Monitor it: reports are noisy, with browser extensions causing many violations. - Deploy in report-only mode. Send
Content-Security-Policy-Report-Onlyfor a week or two on real traffic and fix genuine violations. - Enforce. Switch to
Content-Security-Policy, keep monitoring, and keep a report-only header for the next, stricter version you're testing. - Add the non-script directives.
object-src 'none',base-uri,form-actionandframe-ancestorsare easy wins. - Consider Trusted Types.
require-trusted-types-for 'script'makes DOM XSS sinks such asinnerHTMLreject plain strings, which removes a whole class of client-side bugs; check browser support for your audience before relying on it.
Setting the header in common servers
In nginx, add it in the server block (the always flag sends it on error pages too):
add_header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'" always;In Caddy, use the header directive:
header Content-Security-Policy "default-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'"Static headers like these suit allowlist or hash-based policies; nonce-based policies have to be generated by the application for each response. Our nginx vs Caddy comparison covers each server's header handling in more depth.
Common CSP Mistakes
- Adding `'unsafe-inline'` to make errors go away, which removes most of the XSS protection.
- Allowlisting huge CDNs such as entire Google or cloud storage domains, which host scripts attackers can abuse.
- Static or reused nonces, including nonces baked into cached pages.
- Forgetting directives without fallback, like
base-uri,form-actionandframe-ancestors. - Setting CSP only in a meta tag, where
frame-ancestorsand reporting don't work. - Skipping report-only testing and breaking checkout or login in production.
- Ignoring third-party changes: a tag manager can inject new scripts tomorrow, so monitor reports continuously.
- Treating CSP as a substitute for escaping and sanitising. It isn't. AI-generated code is a common source of unescaped output; our guide to AI-generated code security covers that risk.
FAQ
Is a content security policy necessary?
It isn't required, but it's strongly recommended for any site that handles logins, payments or user content. A strict CSP turns many XSS bugs from account takeovers into harmless blocked scripts, and frame-ancestors prevents clickjacking.
Does CSP completely prevent XSS?
No. It's a mitigation that makes injected scripts much harder to execute. Bugs inside trusted scripts, DOM-based issues and policies with 'unsafe-inline' can still be exploited. Proper output encoding and sanitisation remain essential.
Should I set CSP in a header or a meta tag?
Use the HTTP header. Meta tags work for basic policies but don't support frame-ancestors, reporting or sandbox, and they only apply after the browser reads them.
Do APIs need a content security policy?
JSON APIs aren't rendered as pages, so CSP matters less, but a restrictive policy such as default-src 'none'; frame-ancestors 'none' on API responses is a cheap safeguard if a response is ever opened directly in a browser.
Does CSP slow down my site?
Not noticeably. The browser checks each resource against the policy, which is cheap. The real cost is engineering time to refactor inline scripts and manage third parties.