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
metatag 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.
- The Code
- Policy Tester
- Directive Matcher
Content-Security-Policy: default-src 'self'; img-src 'self' https://images.example.org; frame-ancestors 'self'; object-src 'none'; base-uri 'self'
<head>
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; img-src 'self' https://images.example.org">
</head>
Your page is https://www.example.com/. Edit the policy, or load an example.
| What the page tries to load | Result | Decided by |
|---|---|---|
| Inline script in the page | Blocked | default-src |
| Inline script with nonce="r4nd0m" | Blocked | default-src |
| onclick attribute on a button | Blocked | default-src |
| Script from /app.js (your site) | Allowed | default-src |
| Script from cdn.example.net | Blocked | default-src |
| Stylesheet from /site.css (your site) | Allowed | default-src |
| style attribute on an element | Blocked | default-src |
| Image from /logo.png (your site) | Allowed | img-src |
| Image from images.example.org | Allowed | img-src |
| Image as a data: address | Allowed | img-src |
| Font from fonts.example.com | Allowed | font-src |
| Frame from widgets.example.net | Allowed | frame-src |
| fetch() call to api.example.com | Allowed | connect-src |
5 of 13 blocked.
- Good: No warnings from this simple check.
A simplified model. It handles the common sources (self, none, hosts, schemes, nonces, unsafe-inline) and ignores paths, hashes, strict-dynamic and the more specific directives. Nothing here loads a real resource.
Match each goal to the directive that does it.
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:
| Header | meta tag | |
|---|---|---|
| Covers content loaded before the tag | Yes | No. It must appear early in the head, and it affects only what comes after |
frame-ancestors | Works | Ignored |
sandbox directive | Works | Ignored |
| Reporting directives | Work | Ignored |
| Report-only mode | Yes | No |
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β
| Directive | Controls |
|---|---|
default-src | A fallback for most fetch directives that you do not set yourself |
script-src | JavaScript, including inline scripts and event attributes |
style-src | Stylesheets, style elements, and style attributes |
img-src, font-src, media-src | Images, fonts, audio and video |
connect-src | fetch, XMLHttpRequest, WebSocket, and similar connections |
frame-src | Where your page may load frames from |
frame-ancestors | Who may put your page in a frame (replaces the old X-Frame-Options idea; see iFrame Security) |
object-src | Plugin content (object, embed). Set to 'none' |
base-uri | What a base tag may set. Use 'self' |
form-action | Where forms may submit to (see Secure Forms) |
upgrade-insecure-requests | Ask the browser to load http subresources over https (see Mixed Content) |
sandbox | Applies sandbox rules to the page (see Sandbox Attribute) |
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β
| Source | Meaning |
|---|---|
'self' | Your own origin |
'none' | Nothing at all |
https://cdn.example.net | That exact host |
*.example.org | Any 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
onclickattribute are blocked. That is CSP doing its job. - A script from
cdn.example.netis 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:
- Generate a new, unpredictable value for every response, on the server, with a secure random generator.
- Never reuse a nonce, and never use a fixed one.
r4nd0mabove is only a teaching placeholder. - 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:
- Start in report-only mode. Send
Content-Security-Policy-Report-Onlywith 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). - Watch the Console. Chrome, Firefox, and Safari show CSP violations in DevTools, naming the directive and the blocked source.
- Fix the cause. Move inline code into files, add the hosts you really use, and remove the ones you do not.
- Switch to enforcing by sending
Content-Security-Policy. You can send both headers while you tune a stricter version. - 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.
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β
- Open DevTools, then Network, click the page request, and read Response Headers. Is
Content-Security-Policythere? - Open the Console and reload. CSP violations appear as red messages naming the directive.
- Test every feature: menus, forms, embeds, analytics, fonts, and maps.
- Run your policy through a CSP evaluator tool from a reputable source, and treat its output as advice, not a verdict.
- Review the policy whenever you add a new third-party service.
Best Practicesβ
- Prefer a header to a
metatag. - Start with
default-src 'self', then add only what you need. - Set
object-src 'none',base-uri 'self', andframe-ancestors. - Move inline scripts to files, or use nonces or hashes.
- Avoid
'unsafe-inline'and'unsafe-eval'in script rules. - Do not allow
data:or wildcards for scripts. - Roll out in report-only mode first.
- List hosts as exactly as you can, rather than whole schemes.
- Review the policy when your page changes.
- Keep escaping and sanitising as your main defence.
Quick Checklistβ
- A policy is sent as a header (or a
metatag as a fallback) -
default-srcis set to something narrow -
script-srchas no'unsafe-inline','unsafe-eval', wildcards, ordata: -
object-src 'none',base-uri, andframe-ancestorsare 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β
- Adding
'unsafe-inline'to make a problem go away. - Forgetting the quotes around
'self'or'none'. - Assuming
default-srccoversframe-ancestors,base-uri, andform-action. - Putting
frame-ancestorsin ametatag, where it is ignored. - Whitelisting whole schemes such as
https:. - Reusing or hard-coding a nonce.
- Skipping report-only mode and breaking the live site.
- Allowing a host and never reviewing it again.
- Treating CSP as a substitute for escaping input and output.
- Copying a policy you do not understand.
Practice Timeβ
- In the Policy Tester, load No policy. How many items are blocked? What does the warning say?
- Load Starter policy. Which scripts are blocked, and why?
- Add
https://cdn.example.nettoscript-srcin the Starter policy. What changes? - Load Strict, with a nonce. Which inline script is now allowed? Is the
onclickattribute? - Add
'unsafe-inline'to the nonce policy'sscript-src. Does theonclickattribute start working? Why not? - Load Too loose, and list the warnings it gives.
- Complete the Directive Matcher.
- Bonus: open DevTools on a site you own, read its
Content-Security-Policyheader, 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
metatag 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.