Skip to main content

Content Security Policy (CSP)

Most of this section is about what you write in HTML. A Content Security Policy is different. It is a set of rules you give the browser, telling it which sources it may trust for scripts, styles, images, frames, and more. If an attacker manages to slip a script into your page, CSP can stop the browser from running it.

CSP does not replace good habits like escaping, as taught in XSS Basics. It is a second layer that limits the damage when something goes wrong.

What You Will Learn​

  • What a Content Security Policy is, and how a browser applies it
  • How to send one as a header, and what the meta tag can and cannot do
  • The main directives and source values
  • Why inline scripts are blocked, and how nonces fix that safely
  • How to roll out a policy without breaking your site
  • What CSP does not do

The Big Idea​

Without CSP, the browser runs any script on the page, whoever put it there. With CSP, the browser first checks a guest list. A script, image, or frame is loaded only if its source is on the list for that kind of content.

Response header (recommended)
Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.org; frame-ancestors 'self'; object-src 'none'; base-uri 'self'
index.html (limited: the meta tag)
<head>
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; img-src 'self' https://images.example.org">
</head>

Header or Meta Tag?​

The proper way is an HTTP response header set by your server or hosting service.

You can also put a policy in a meta tag with http-equiv="Content-Security-Policy", which is useful when you cannot set headers, such as on a simple static host. But a meta policy has real limits:

Headermeta tag
Covers content loaded before the tagYesNo. It must appear early in the head, and it affects only what comes after
frame-ancestorsWorksIgnored
sandbox directiveWorksIgnored
Reporting directivesWorkIgnored
Report-only modeYesNo

If your host lets you set headers (many have a settings page or a headers file), prefer the header.

How a Policy Is Written​

A policy is a list of directives separated by semicolons. Each directive has a name and a list of allowed sources:

script-src 'self' https://cdn.example.net; img-src *.example.org data:

The most useful directives​

DirectiveControls
default-srcA fallback for most fetch directives that you do not set yourself
script-srcJavaScript, including inline scripts and event attributes
style-srcStylesheets, style elements, and style attributes
img-src, font-src, media-srcImages, fonts, audio and video
connect-srcfetch, XMLHttpRequest, WebSocket, and similar connections
frame-srcWhere your page may load frames from
frame-ancestorsWho may put your page in a frame (replaces the old X-Frame-Options idea; see iFrame Security)
object-srcPlugin content (object, embed). Set to 'none'
base-uriWhat a base tag may set. Use 'self'
form-actionWhere forms may submit to (see Secure Forms)
upgrade-insecure-requestsAsk the browser to load http subresources over https (see Mixed Content)
sandboxApplies sandbox rules to the page (see Sandbox Attribute)
info

default-src is a fallback only for the fetch-type directives (scripts, styles, images, fonts, frames, connections, and so on). It does not cover base-uri, form-action, or frame-ancestors. Set those yourself.

Source values​

SourceMeaning
'self'Your own origin
'none'Nothing at all
https://cdn.example.netThat exact host
*.example.orgAny subdomain of that host (not the bare domain)
https:Any https address (very broad)
data:data: addresses (fine for small images, dangerous for scripts)
'nonce-...'An inline element carrying the matching nonce
'sha256-...'An inline script or style whose text hashes to this value
'unsafe-inline'Any inline code. Weakens protection
'unsafe-eval'eval and similar. Weakens protection

Note the quotes. Keywords such as 'self' and 'none' must be written with single quotes inside the policy, while hosts and schemes are not quoted.

Try It: The Policy Tester​

Open the Policy Tester tab. It lists thirteen things a page might try to load. Pick Starter policy and read the results:

  • Scripts from your own site are allowed, but the inline script and the onclick attribute are blocked. That is CSP doing its job.
  • A script from cdn.example.net is blocked, because it is not on the list.

Now load Strict, with a nonce, and compare. Then load Too loose, and read the warnings.

Inline Scripts: Why They Are Blocked​

By default, a useful CSP blocks inline scripts and event attributes. This is deliberate, because injected XSS is usually an inline script. The cost is that you must move your own code into files, and replace onclick="..." attributes with addEventListener.

<!-- Blocked by a strict CSP -->
<button onclick="save()">Save</button>

<!-- Allowed: the code lives in a file from your own origin -->
<button id="save">Save</button>
<script src="/app.js"></script>

If you must keep a specific inline script, use a nonce or a hash, never 'unsafe-inline'.

Nonces​

A nonce is a random value that the server generates for each response. It appears in the header and on the trusted script:

Content-Security-Policy: script-src 'self' 'nonce-r4nd0m'
<script nonce="r4nd0m">
// allowed, because the nonce matches
</script>

An injected script has no way to know the nonce, so it is blocked. Three rules make this safe:

  1. Generate a new, unpredictable value for every response, on the server, with a secure random generator.
  2. Never reuse a nonce, and never use a fixed one. r4nd0m above is only a teaching placeholder.
  3. A nonce needs a server that builds the page. A fully static page cannot use one. For that case, use a hash, or move scripts to files.

When a policy contains a nonce or a hash, browsers ignore 'unsafe-inline' in that directive. The Policy Tester shows this in action.

Rolling Out a Policy Safely​

A strict policy can break pages in ways you do not expect. Roll it out in steps:

  1. Start in report-only mode. Send Content-Security-Policy-Report-Only with the same policy. The browser reports what would have been blocked, without blocking anything. Reports go to an endpoint you set up with a reporting directive (check your provider's current documentation for the exact setup).
  2. Watch the Console. Chrome, Firefox, and Safari show CSP violations in DevTools, naming the directive and the blocked source.
  3. Fix the cause. Move inline code into files, add the hosts you really use, and remove the ones you do not.
  4. Switch to enforcing by sending Content-Security-Policy. You can send both headers while you tune a stricter version.
  5. Keep watching. New scripts, new third-party tools, and new embeds all need a policy update.

Several policies can be sent at once, and the browser applies all of them. A resource must pass every one.

A Starter Policy​

This is a reasonable starting point for a simple site that serves its own scripts and styles. Adjust the hosts to match what your page really uses:

Content-Security-Policy:
default-src 'self';
img-src 'self' data: https://images.example.org;
frame-src https://widgets.example.net;
connect-src 'self';
object-src 'none';
base-uri 'self';
form-action 'self';
frame-ancestors 'self'

If your site uses inline style attributes or style elements, CSP will block them. Moving styles into a stylesheet is the best fix, and a nonce or hash for a specific style element is the next best. Avoid giving up with 'unsafe-inline' in style-src unless you accept the trade-off.

What CSP Does Not Do​

  • It is not a replacement for escaping and sanitising. It is a safety net. See XSS Basics.
  • It cannot stop a script you allowed, from a host you trust, from misbehaving. If a trusted host is hacked, your site is affected.
  • It does not stop all attacks, such as phishing links, or abuse of a legitimate feature of your own site.
  • It does not hide anything from the visitor. It restricts what the browser loads, and does not encrypt or conceal.
  • Wide wildcards weaken it. A policy that allows https: for scripts allows scripts from almost anywhere.
warning

Do not copy a long policy from the internet without understanding it. An overly loose policy gives a false sense of safety, and an overly strict one breaks your site. Start from your actual needs, test in report-only mode, and tighten step by step.

Checking Your Setup​

  1. Open DevTools, then Network, click the page request, and read Response Headers. Is Content-Security-Policy there?
  2. Open the Console and reload. CSP violations appear as red messages naming the directive.
  3. Test every feature: menus, forms, embeds, analytics, fonts, and maps.
  4. Run your policy through a CSP evaluator tool from a reputable source, and treat its output as advice, not a verdict.
  5. Review the policy whenever you add a new third-party service.

Best Practices​

  1. Prefer a header to a meta tag.
  2. Start with default-src 'self', then add only what you need.
  3. Set object-src 'none', base-uri 'self', and frame-ancestors.
  4. Move inline scripts to files, or use nonces or hashes.
  5. Avoid 'unsafe-inline' and 'unsafe-eval' in script rules.
  6. Do not allow data: or wildcards for scripts.
  7. Roll out in report-only mode first.
  8. List hosts as exactly as you can, rather than whole schemes.
  9. Review the policy when your page changes.
  10. Keep escaping and sanitising as your main defence.

Quick Checklist​

  • A policy is sent as a header (or a meta tag as a fallback)
  • default-src is set to something narrow
  • script-src has no 'unsafe-inline', 'unsafe-eval', wildcards, or data:
  • object-src 'none', base-uri, and frame-ancestors are set
  • Inline code uses nonces or hashes, or lives in files
  • You tested in report-only mode first
  • The Console shows no unexpected violations

Security and Privacy Notes​

  • Reports can contain page addresses. If you collect violation reports, they may include URLs that hold personal information. Store them carefully, and keep them only as long as needed.
  • Third-party hosts you allow can see your visitors. Each host in your policy is a company that receives requests from your visitors' browsers. Allow as few as possible.
  • A nonce is only secret within one response. Never put it in a place that is cached and shared between visitors.
  • Test only your own site, or sites you have permission to test.

Global Audience Notes​

  • Different regions use different services, such as maps, payments, and fonts. A policy that works at home can block a service your visitors in another country use, so test with real flows.
  • CDNs and fonts can be slow or blocked in some places. Serving fonts and scripts from your own origin is simpler for a policy, and often faster.
  • Error messages from CSP are in English in DevTools. Make sure your team can read them, and that visitor-facing errors on your site remain in the page's own language.

Common Mistakes to Avoid​

  1. Adding 'unsafe-inline' to make a problem go away.
  2. Forgetting the quotes around 'self' or 'none'.
  3. Assuming default-src covers frame-ancestors, base-uri, and form-action.
  4. Putting frame-ancestors in a meta tag, where it is ignored.
  5. Whitelisting whole schemes such as https:.
  6. Reusing or hard-coding a nonce.
  7. Skipping report-only mode and breaking the live site.
  8. Allowing a host and never reviewing it again.
  9. Treating CSP as a substitute for escaping input and output.
  10. Copying a policy you do not understand.

Practice Time​

  1. In the Policy Tester, load No policy. How many items are blocked? What does the warning say?
  2. Load Starter policy. Which scripts are blocked, and why?
  3. Add https://cdn.example.net to script-src in the Starter policy. What changes?
  4. Load Strict, with a nonce. Which inline script is now allowed? Is the onclick attribute?
  5. Add 'unsafe-inline' to the nonce policy's script-src. Does the onclick attribute start working? Why not?
  6. Load Too loose, and list the warnings it gives.
  7. Complete the Directive Matcher.
  8. Bonus: open DevTools on a site you own, read its Content-Security-Policy header, and explain each directive in your own words.

Quick Recap​

Click a question to check your answer.

1. What is a Content Security Policy?

A set of rules, sent as a header (or a meta tag), that tells the browser which sources it may load scripts, styles, images, frames, and more from.

2. Why is a header better than a meta tag?

A meta policy only affects what follows it, and ignores frame-ancestors, sandbox, and reporting directives. A header covers the whole page and supports all directives.

3. What does default-src do?

It is a fallback for most fetch directives you do not set. It does not cover base-uri, form-action, or frame-ancestors.

4. Why are inline scripts blocked?

Injected XSS is usually an inline script. Blocking inline code stops it. Your own code goes in files, or uses a nonce or hash.

5. What makes a nonce safe?

It is unpredictable, generated by the server for each response, and never reused, so an attacker cannot guess it.

6. How do you roll out a policy safely?

Start in report-only mode, read the violations, fix their causes, then enforce. Keep monitoring as the site changes.

Key Takeaways​

  • CSP is a guest list for the browser. It limits where content may come from.
  • Send it as a header. The meta tag is a limited fallback.
  • Start with default-src 'self', then add what you truly need.
  • Avoid 'unsafe-inline', 'unsafe-eval', data:, and wildcards for scripts.
  • Use nonces or hashes for the inline code you must keep.
  • Roll out in report-only mode, then enforce.
  • CSP is a second layer. Escaping and sanitising remain the first.

Next up: Mixed Content, where you will learn what happens when a secure page loads something over plain http, and how browsers and policies deal with it.