Content Security Policy (CSP)

CSP (Content Security Policy) is a header holding the list of sources a page may use. The browser refuses the rest, including injected XSS scripts. The…

You've escaped every input, but you missed one comment field. A comment holding <script>alert(1)</script> then runs in the browser of every user who opens that page. For moments like this you need a second layer, one that still stops the attack when the escaping misses something.

That layer is CSP (Content Security Policy): a response header holding the list of sources a page may use. It says where scripts may come from, where images may come from, and which servers the page may contact. The browser refuses everything not on the list, including a script an attacker added through XSS. Picture the guest list at the door of a wedding hall. The security guard only lets in names on the list. An uninvited guest is refused, however well they dress. The guest list is CSP, the guard is the browser, and the uninvited guest is the attacker's injected script.

What a policy looks like

This is an example CSP header. The part after Content-Security-Policy: is called the policy:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com

The sources you'll use most:

Source Meaning
'self' only from the page's own origin (same scheme, host, and port). Subdomains don't count
https://cdn.example.com from that host only
data: data: URLs, such as a small image written straight into the HTML
'none' from nowhere at all
'nonce-r4nd0m' an inline script carrying the attribute nonce="r4nd0m"

Keywords such as 'self' and 'none' must be in single quotes. Hosts and data: are written without quotes.

Directives and the fallback to default-src

Each kind of source has its own directive:

Directive Controls
default-src the fallback for any -src directive you didn't write
script-src JavaScript
style-src CSS
img-src images
connect-src fetch, XHR, and WebSocket
font-src fonts
frame-ancestors who may show this page in an iframe

A directive you didn't write falls back to default-src, which is the backup (the fallback). The exceptions are frame-ancestors, base-uri (limits the address for the <base> tag) and form-action (limits where forms may be sent): those three have no fallback. Here's the result for the page https://myapp.com with only default-src 'self':

On the page Governed by Result
<script src="/app.js"> default-src 'self' loads
<script src="https://cdn.example.com/chart.js"> default-src 'self' blocked
<img src="https://images.com/banner.jpg"> default-src 'self' blocked
<img src="data:image/gif;base64,..."> default-src 'self' blocked, 'self' doesn't cover data:
fetch("https://api.myapp.com/orders") default-src 'self' blocked, different host

So the banner.jpg image doesn't show. img-src isn't written, so default-src 'self' is used, and https://images.com isn't your own origin. Chrome writes in the console:

Refused to load the image 'https://images.com/banner.jpg' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

To load everything, write the directives one by one:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com; img-src 'self' data: https://images.com; connect-src 'self' https://api.myapp.com

Inline scripts: a nonce, not unsafe-inline

As soon as there's a script-src (or default-src) without 'unsafe-inline', the browser refuses every script written directly in the HTML (an inline script): <script>...</script> as well as onclick="...". That rule is what stops XSS. A comment holding <script>alert(1)</script> doesn't run, and Chrome writes Refused to execute inline script because it violates the following Content Security Policy directive: ....

So what about your own inline scripts? Use a nonce: a new random value the server creates for every response. The nonce is written in the header and on your script tag. In this example, the first line (written as an HTML comment) is the CSP header:

<!-- Content-Security-Policy: script-src 'self' 'nonce-r4nd0m' -->
<script nonce="r4nd0m">initCart()</script>  <!-- runs -->
<script>alert(1)</script>                   <!-- blocked: no nonce -->

The attacker doesn't know that response's nonce, so their injected script can't run with it. In production the nonce must be random and change with every response, not a fixed r4nd0m like in this example.

Two keywords undo this protection:

So script-src 'unsafe-inline' 'unsafe-eval' allows inline scripts and eval, and XSS works again as if there were no CSP. One note: once the source list holds a nonce, the browser ignores 'unsafe-inline'.

A static page (the same HTML file for every visitor) cannot make a new nonce for every response. For a page like that, use a hash: the SHA-256 fingerprint of the inline script's content, written in the policy. Content that differs by even one character is refused:

<!-- Content-Security-Policy: script-src 'sha256-Xak+25WM8/tpvDC/DGH1nnLy2ZxujqBIgx9RQz5MXZc=' -->
<script>initCart()</script>  <!-- runs: the hash of its content matches -->
<script>alert(1)</script>    <!-- blocked: different hash -->

A summary of the options for script-src:

Approach When to pick it
A host list, 'self' https://cdn.example.com a small site with few scripts. But a public CDN also serves other people's scripts, which an attacker can load
Strict CSP: 'nonce-...' 'strict-dynamic', plus object-src 'none'; base-uri 'none' the server builds the HTML for each request. Recommended by web.dev: a script with the nonce may load other scripts, no host list needed
A hash, 'sha256-...' a static page whose inline scripts never change

This lesson uses host lists so the directives are easy to read. For a real site, start from a strict CSP.

Building the policy string with JavaScript

On the server, a policy is often built from an object, then turned into a string. This is the buildCSP function from the exercise:

function buildCSP(directives) {
  return Object.entries(directives)
    .map(([name, sources]) => name + " " + sources.join(" "))
    .join("; ");
}

console.log(buildCSP({
  "default-src": ["'self'"],
  "script-src": ["'self'", "https://cdn.example.com"]
}));
// default-src 'self'; script-src 'self' https://cdn.example.com

This table shows the result of each step for the object above:

Step Result
Object.entries(directives) [["default-src", ["'self'"]], ["script-src", ["'self'", "https://cdn.example.com"]]]
.map(...) ["default-src 'self'", "script-src 'self' https://cdn.example.com"]
.join("; ") "default-src 'self'; script-src 'self' https://cdn.example.com"

Header, meta tag, and Report-Only

CSP works best sent as a header. When you can't set headers, use a meta tag in <head>:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

A meta tag only covers the page's content after the tag, and can't use frame-ancestors, report-uri, or Report-Only mode.

Before blocking in production, try it first with the Report-Only header. With this header, the browser still loads everything. But the browser logs each violation (a source the policy would block) in the console, starting with [Report Only], and sends a report to the URL in report-uri:

Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report

report-uri is deprecated (no longer recommended). Its replacement is report-to, which names an endpoint from the Reporting-Endpoints header. Browsers that support report-to (Chrome 70, Safari 16.4, Firefox 149) ignore report-uri. Write both for older browsers:

Reporting-Endpoints: csp="https://myapp.com/csp-report"
Content-Security-Policy-Report-Only: default-src 'self'; report-uri /csp-report; report-to csp

In this example, report-to csp points to the name csp in Reporting-Endpoints, which is https://myapp.com/csp-report. Once the reports stay clean for a few days, rename the header to Content-Security-Policy.

⚠️ Slips that keep a CSP from working

TL;DR: CSP (Content Security Policy) is a header holding the list of sources a page may use. The browser refuses the rest, including injected XSS scripts. The header's content (the policy) is made of directives (rules for one kind of source) separated by ; . Each directive holds a name, then sources separated by spaces, such as default-src 'self'; script-src 'self' https://cdn.example.com. 'self' means only from your own origin. img-src controls images, script-src scripts, connect-src fetch, and any directive you didn't write falls back to default-src. Inline scripts (scripts written directly in the HTML) are blocked unless they carry a nonce, a random value that is new in every response. 'unsafe-inline' and 'unsafe-eval' undo the protection. Send CSP as a header, or as <meta http-equiv="Content-Security-Policy" content="...">. Test it first with Content-Security-Policy-Report-Only, which only logs violations and blocks nothing.

⚡ A list of allowed sources

Write:

Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.com

Meaning: CSP (Content Security Policy) is a header holding the list of sources a page may use. The browser refuses everything not on the list. A CSP holds directives (rules for one kind of source) separated by ; , and each directive holds a name, then sources separated by spaces. Here script-src is for scripts only, and default-src covers every other kind of source. Keywords such as 'self' (the page's own origin) must be in single quotes.

⚡ The fallback to default-src

Meaning: A directive you didn't write falls back to default-src, which is the backup (the fallback). With only default-src 'self', an image from https://images.com is blocked, because img-src (the directive for images) isn't written. The exceptions are frame-ancestors, base-uri, and form-action: those three have no fallback.

⚡ A nonce, not unsafe-inline

Write:

<script nonce="r4nd0m">initCart()</script>  <!-- runs -->
<script>alert(1)</script>                   <!-- blocked: no nonce -->
Guess first: 'unsafe-inline' allows every inline script (a script written directly in the HTML), and 'unsafe-eval' allows eval(), which runs text as code. What's the problem with script-src 'unsafe-inline' 'unsafe-eval'?

That directive allows inline scripts and eval, the attacker's included. XSS works again as if there were no CSP.

Meaning: A nonce is a new random value the server creates for every response, written in the CSP header and on your own script tag. A script without the matching nonce is blocked. The attacker doesn't know the nonce, so their injected script can't run.

⚡ Try it first with Report-Only

Meaning: With the Content-Security-Policy-Report-Only header, the browser still loads everything, but logs each violation (a source the CSP would block). Once there are no violations for a few days, rename the header to Content-Security-Policy.

What you will learn