Imagine your website gets hacked. An attacker inserts a malicious script (JavaScript code) through a form field that nobody checked (an XSS attack). The script can steal users' cookies (the sign that a user is logged in), send users to a fake site, or empty their balance. One of the most effective defences is Content Security Policy (CSP). CSP is an HTTP header (a message from the server, your site's computer) that tells the browser which sources the scripts on this page may come from. The browser blocks a script from another domain (another site's address) before it can run.
🤔 Defence in depth. CSP is only one of several layers of protection. The other layers: input sanitisation (cleaning the input), output escaping (turning special characters into plain text) and HttpOnly cookies (JavaScript can't read them). CSP is the last layer: even when every other layer has failed, CSP can still refuse a malicious script. Any serious app needs it.
CSP Syntax with a Meta Tag
CSP can also be written as a meta tag:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self'">
The content attribute holds a list of rules, separated by semicolons. Each rule is called a directive: the name of a kind of resource (a file the page loads), then the sources allowed for it.
Important Directives
default-src: the source for any kind of resource that has no rule of its ownscript-src: where JavaScript may come fromstyle-src: where CSS may come fromimg-src: where images may come fromfont-src: where fonts may come fromconnect-src: which addresses a script may contact (APIs)
Values You Can Use
'self': only from your own domain'none': not allowed at all'unsafe-inline': allows scripts and styles written directly in the HTML (inline)https:: only over HTTPShttps://cdn.example.com: only from that domain
Why Does CSP Matter?
Without CSP, a script that an attacker inserts runs freely on your page. CSP stops scripts you haven't allowed from running.
An allowlist like the example above is enough for a static site (one with no program on the server) that loads no scripts from other companies. But a long list of domains is often unsafe. So against XSS, MDN (Mozilla's web guide) now recommends a strict CSP. Each time it sends a page, the server makes a new random code (a nonce) and writes it in the header, such as script-src 'nonce-random123'; object-src 'none'; base-uri 'none'. Only a script that carries that code, <script nonce="random123">, may run.
🎭 An everyday analogy
CSP is like the guest list at a wedding. Only people whose names are on the list may enter. An uninvited guest is refused, even in an expensive suit and with a present. The same happens to a malicious script that an attacker inserts: its source isn't on the CSP list, so the browser blocks it right away.
⚠️ Common traps
'unsafe-inline'also allows the scripts an attacker inserts. Don't use it unless you really have to. Use anonceor ahashinstead: a permission code for each inline script of your own, so only those scripts pass.- CSP in a meta tag VS an HTTP header:
Content-Security-Policy-Report-Only, violation reports,frame-ancestorsandsandboxonly work in the header. In a meta tag, all four are ignored. A meta tag suits a static site that can't set headers. - Test it first: the
Content-Security-Policy-Report-Onlyheader logs violations without blocking anything. - Inline event handlers (
onclick="...") are blocked by a strict CSP. Attach the action from a JS file withaddEventListener. - Third-party CDNs (other companies' servers, such as Google Fonts and jQuery) must be listed in
script-src/style-src. Font files from Google Fonts also needfont-src https://fonts.gstatic.com. 'self'means same origin only (the same protocol such as https, the same domain, and the same port, the number after the domain): another subdomain, such as cdn.example.com for example.com, counts as different.upgrade-insecure-requestsautomatically changes http: to https: for every resource.- A report endpoint: an address on a server where the browser reports everything CSP blocked.
report-uriis deprecated, and its replacement isreport-to(with aReporting-Endpointsheader). Write both until every browser supportsreport-to.
TL;DR: CSP is an allowlist: the sources of resources (scripts, styles, images and so on) that the browser may load. It is the last defence against XSS (an attacker inserting a malicious script). Set it with an HTTP header (a message from the server, supports every feature) or <meta http-equiv>. Important rules (directives): default-src, script-src, style-src, connect-src. Values: 'self' (your own domain), 'unsafe-inline' (avoid it: inserted scripts are allowed too), or a specific domain. A strict CSP with a nonce (a new random code for each page) is safer. Test first with the Content-Security-Policy-Report-Only header (it doesn't work in a meta tag), which logs without blocking. A strict CSP blocks inline onclick, so attach actions from a JS file (addEventListener). A <style> inside the HTML is blocked too when style-src doesn't include 'unsafe-inline'. The example in this lesson doesn't include it, so its CSS goes in a separate file on your own domain.
⚡ A guest list for scripts
Write:
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self'">
Meaning: CSP is a guest list: the browser only loads scripts, CSS and images from the sources on that list. A script that an attacker inserts (XSS) from another domain is blocked before it can run. It is the last layer of defence. CSP in an HTTP header (a message from the server) supports every feature. A meta tag suits a static site (one with no program on the server) that can't set headers.
⚡ 'self' means your own domain
Guess first: does a script from another subdomain (such as cdn.example.com for example.com) pass 'self'?
No. 'self' means exactly the same address only, so another subdomain counts as different.
Meaning: 'self' means only from your own domain, and 'none' means not allowed at all. script-src is for JavaScript, style-src is for CSS, and default-src is for any other kind that has no rule of its own.
⚡ Inline gets blocked too
Guess first: does onclick="..." still work under a strict CSP?
No. onclick is written directly in the HTML (inline), so it's blocked too. Attach the action from a JS file with addEventListener.
Meaning: 'unsafe-inline' also allows the scripts an attacker inserts, so avoid it. Test first with the Content-Security-Policy-Report-Only header, which logs violations without blocking. This test mode doesn't work in a meta tag.