Cloud & app security

What Is Content Security Policy (CSP)? How It Stops XSS Attacks

CSP is the browser's allowlist for your website: it decides which scripts may run and blocks the rest. Here is how it works and how to deploy it safely.

Cysoro Security TeamPublished · 8 min read
Content-Security-Policyscript-src 'nonce-…'object-src 'none'base-uri 'none'✓ Allowed script✕ Blocked: evil.js CLOUD & APP SECURITY ContentSecurity Policy — the browser's allowlist.
Quick answer

Content Security Policy (CSP) is an HTTP response header that tells a browser which sources of scripts, styles, images and other resources a page may load, blocking everything else. Its main job is to limit cross-site scripting: even if an attacker injects code, the browser refuses to run it without an allowed source, nonce or hash.

Key takeaways

  • CSP is a header that allowlists where scripts, styles, images and frames may come from — anything not listed is blocked by the browser.
  • A strict CSP uses a random per-response nonce or a hash, plus object-src 'none' and base-uri 'none', and avoids 'unsafe-inline'.
  • Roll out in report-only mode first, fix the violations, then enforce — and keep sanitizing input, because CSP does not remove the XSS bug.

Imagine your website has a cross-site scripting flaw — an attacker manages to slip their own JavaScript into a page your visitors load. Without CSP, that script runs with full access to the page. With CSP, the browser checks the script against your allowlist first, and refuses to run it.

What is Content Security Policy?

Content Security Policy (CSP) is an HTTP response header that tells a browser which sources a page may load scripts, styles, images, fonts, frames and other resources from — and blocks everything else.

The policy is a series of directives separated by semicolons. Each directive names one resource type and the sources allowed for it. For example, Content-Security-Policy: default-src 'self'; img-src 'self' example.com tells the browser to load resources only from the same origin, except images, which may also come from example.com.

CSP is defined by the W3C in Content Security Policy Level 3, and MDN describes its primary use as controlling which resources a document can load as a defence against cross-site scripting (XSS).

CSP is delivered in the HTTP response header, and MDN recommends setting it on all responses, not just the main document. You can also deliver it in a meta element, but that form does not support all features. Check your own site's headers in seconds with our free security headers checker.

How does CSP work?

The server sends the header with the page, and the browser checks every resource the page tries to use against the policy before loading or running it. Anything not allowed is blocked, and the browser logs a violation in the console.

How CSP protects a pageYour serversends the page plusa CSP headerBrowser checksevery script, style,image and frameAllowed: loadsNot allowed: blockedAn injected script from evil.example.com never runs — it is not on the list.
Your server sets the policy; the browser enforces it on every resource. Illustration by Cysoro.

An XSS attack works when a site takes attacker-controlled input — a URL parameter, a comment, a profile field — and includes it in a page without sanitizing it, so the attacker's code runs in the victim's browser. That code can read page content, access local storage, and make requests with the user's credentials.

CSP defends in depth: even if sanitization fails, the injected script is blocked because it is not from an allowed source, has no valid nonce, and is not inline-approved code.

MDN is explicit on the limit, though: setting a CSP is not an alternative to sanitizing input. Websites should sanitize input and set a CSP. OWASP makes the same point — CSP should not be relied on as the only defensive mechanism against XSS.

What are the main CSP directives?

Directives fall into groups: fetch directives control where each resource type may come from, document directives control the page itself, and reporting directives say where violations go. You only need a handful to write a good policy.

DirectiveWhat it controlsTypical value
default-srcFallback for any resource type without its own directive'self'
script-srcWhich scripts may run'nonce-{RANDOM}' 'strict-dynamic'
style-srcWhich stylesheets may load'self' or a nonce
img-srcWhich images may load'self' plus trusted hosts
connect-srcWhere scripts may fetch data (XHR, fetch, WebSocket)'self' plus API hosts
font-srcWhich fonts may load'self'
object-srcPlugins and embedded objects'none'
base-uriWhich URLs the base element may use'none'
frame-ancestorsWhich sites may embed this page in a frame'none' or 'self'
form-actionWhere forms may submit'self'

Source expressions include 'self' (same origin), 'none' (block entirely), hostnames such as example.com or wildcards such as *.example.org, schemes such as https:, and the special values for nonces and hashes. The keyword 'none' cannot be combined with other sources in the same directive — if you list anything alongside it, the extras are ignored.

Two directives deserve special attention. frame-ancestors 'none' stops clickjacking by preventing any site from framing your page, and MDN calls it a more flexible replacement for the older X-Frame-Options header. object-src 'none' blocks plugins and embedded objects entirely, which OWASP recommends because there is rarely a legitimate need for them.

What is a strict CSP, and why is it recommended?

A strict CSP allows scripts only if they carry a random per-response nonce or a matching hash, instead of trusting a list of hostnames. MDN and OWASP both recommend nonce- or hash-based policies as current best practice.

The problem with hostname allowlists is that they are easy to bypass: if an allowed host serves any user-controlled content, an attacker can host their script there and it passes the allowlist. Google's research on this, titled "CSP Is Dead, Long Live CSP", showed how often allowlist policies could be bypassed.

OWASP warns that a non-strict policy that is too granular or permissive is likely to lead to bypasses. A strict policy is, in OWASP's words, much easier to deploy correctly.

The minimal strict policy MDN and OWASP recommend looks like this:

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

The nonce must be different for every HTTP response and must not be predictable — MDN states this plainly. The server generates it, puts it in the header, and adds the same value as a nonce attribute on each legitimate script tag.

An injected script cannot know the nonce, so the browser refuses to run it. The 'strict-dynamic' keyword lets scripts loaded by a trusted script load their own dependencies without listing every host.

Hashes work differently: the server hashes each script's contents (SHA-256, SHA-384 or SHA-512) and lists the hash in the policy. The browser hashes the script it receives and runs it only if the values match.

Hashes suit static pages, because the policy never changes; nonces suit dynamic pages, because the server generates a fresh value per response. Any change to a hashed script — even whitespace — changes its hash and breaks it.

Why should you avoid 'unsafe-inline'?

The 'unsafe-inline' keyword allows inline scripts, inline event handlers and javascript: URLs to run. MDN warns developers to avoid it, because it defeats much of the purpose of having a CSP.

Inline JavaScript is one of the most common XSS vectors. If your policy allows it, an attacker who injects a script tag or an onerror handler into your page gets their code executed — exactly the outcome CSP exists to prevent. A policy such as default-src 'self' 'unsafe-inline' still blocks remote scripts, but leaves the front door open.

If a directive contains a nonce or hash, browsers ignore 'unsafe-inline' for that directive, which is what makes the strict policy work: older browsers that do not understand nonces fall back to the allowlist, while modern browsers enforce the nonce. The same logic applies to 'unsafe-eval', which allows eval() and the Function() constructor — avoid it unless a library genuinely needs it, and look for an alternative first.

How do you roll out CSP without breaking your site?

Roll out in report-only mode first. Send the policy in a Content-Security-Policy-Report-Only header: the browser does not block anything, but sends violation reports to the endpoint you name. Fix the violations, then switch to the enforcing header.

A safe CSP rollout in four steps1Report-onlynothing blocked,violations logged2Review reportsfind scripts andresources you missed3Fix the policyadd nonces, removeinline code4Enforceswitch to the realheader, keep watchingKeep report-only running on a staging site after you enforce in production.
Report first, enforce second — never the other way round. Illustration by Cysoro.
  1. Start with a basic policy in report-only mode. A reasonable starting point for a site that loads everything from its own origin is default-src 'self'; frame-ancestors 'self'; form-action 'self'; in report-only mode.
  2. Set up a reporting endpoint. MDN recommends the Reporting API: declare an endpoint in a Reporting-Endpoints header and name it in the report-to directive. Older deployments used report-uri.
  3. Review the violations. Every blocked resource your site actually needs shows up as a report. Add it properly — with a nonce or a named host — rather than widening the policy with a wildcard.
  4. Move to a strict nonce-based policy once the reports are clean, and keep monitoring. Third-party scripts change, marketing tags appear, and a policy that was clean last month can break next month.

OWASP warns against one shortcut: do not use middleware that automatically adds a nonce to every script tag, because scripts an attacker injects would receive the nonce too. Nonces must be added by your templating engine, only to scripts you intend to run.

What are the common CSP mistakes?

Most broken or bypassable policies fail in the same few ways. Avoid these and your policy will be stronger than most sites on the web.

  • Using 'unsafe-inline' to make errors go away. It silences the console and the protection at the same time. Fix the inline code instead.
  • Allowing broad hostnames such as *.googleapis.com or a CDN wildcard. Any content hosted there — including attacker-controlled content — becomes trusted.
  • Forgetting the header on some responses. CSP must be sent on all responses, not just the home page. An unprotected page is an open door.
  • Using the obsolete X-Content-Security-Policy or X-WebKit-CSP headers. OWASP warns these are obsolete, limited and buggy. Use the standard header.
  • Setting a policy once and never reviewing it. New scripts, analytics tags and embeds arrive constantly. Review violation reports regularly.
  • Treating CSP as the fix for XSS. CSP limits exploitation; it does not remove the injection flaw. Keep encoding output and validating input.

How does CSP compare with other security headers?

CSP is one header in a set that together harden a site. It is the most powerful, but it works best alongside the others — and our security headers checker reports on the whole set at once.

Strict-Transport-Security (HSTS) forces HTTPS so attackers cannot downgrade connections; CSP's upgrade-insecure-requests directive can upgrade HTTP resource loads to HTTPS. X-Content-Type-Options: nosniff stops browsers guessing content types, which prevents some script-injection tricks. Referrer-Policy controls what referrer information leaks to other sites. Permissions-Policy restricts powerful browser features such as camera and geolocation.

For the full picture, see our website security overview.

Check that your TLS is sound with the free SSL checker.

The bottom line

Content Security Policy is the browser's allowlist for your site: it decides what may run, and blocks the rest. A strict, nonce-based policy turns many XSS bugs from an account takeover into a blocked request and a console error.

Start in report-only mode, move to a strict policy, avoid "unsafe-inline", and keep sanitizing input — CSP is your second layer, not your only one. Run the free security headers checker to see whether your site already sends a CSP, and what it is missing.

Frequently asked questions

What is Content Security Policy in simple terms?

CSP is a set of instructions your server sends with each page, telling the browser which sources may supply scripts, styles, images and frames. If something tries to load from a source that is not on the list, the browser blocks it.

Does CSP prevent cross-site scripting?

CSP limits the damage from XSS by blocking injected scripts from running, but it does not fix the underlying injection bug. You still need to sanitize and encode user input; CSP is a second layer of defence on top of that.

What is a strict CSP?

A strict CSP allows scripts only if they carry a random per-response nonce or a matching hash, and blocks plugins and inline code. MDN and OWASP both recommend nonce- or hash-based policies as current best practice, because allowlists of hostnames can often be bypassed.

What does default-src 'self' mean?

It means resources may load only from the same origin as the page itself, unless a more specific directive says otherwise. It is the fallback directive: any resource type without its own directive follows default-src.

How do I add CSP to my website?

Send a Content-Security-Policy HTTP response header from your server on every response, starting with Content-Security-Policy-Report-Only to collect violations without breaking the site. Then fix the violations and switch to the enforcing header.

What is the difference between CSP and X-Frame-Options?

Both can stop clickjacking, but CSP's frame-ancestors directive is more flexible and is the modern replacement. MDN recommends setting frame-ancestors to 'none' unless your page needs to be embedded in another site.

Can I use CSP with a meta tag instead of a header?

Yes, with a meta element using http-equiv, which suits static sites and single-page apps. But the meta-tag form does not support all features, including frame-ancestors, report-only mode and sandbox, so the header is preferred.

Will CSP break my website?

It can, if the policy blocks a script, font or image your site needs. That is why you should roll it out in report-only mode first, watch the violation reports, fix the policy, and only then enforce it.

Sources

  1. MDN — Content Security Policy (CSP)
  2. OWASP — Content Security Policy Cheat Sheet
  3. W3C — Content Security Policy Level 3
  4. MDN — Content-Security-Policy header reference
  5. Google — CSP Is Dead, Long Live CSP (strict CSP guidance)
Written & fact-checked byCysoro Security Team

The engineers and analysts who build Cysoro's domain scanner, email-authentication checks and free security tools. We test what we write about every day — SPF, DKIM, DMARC, certificates, look-alike domains and phishing — and check each guide against the relevant standards, government guidance and vendor documentation.

  • Email authentication
  • Phishing & BEC
  • Domain & DNS security
  • Small-business security

Checked against MDN's CSP guide and header reference, the OWASP Content Security Policy Cheat Sheet, and W3C CSP Level 3.

How we write and fact-check →

Free tools for this topic

No account needed.

See where your domain stands

Free for up to 3 domains. No card, no installs.

Start free