What you'll learn: By the end of this lesson you will be able to read and write a Content Security Policy (CSP), explain how the browser checks each load against a directive and its fallback, choose between an allowlist, a nonce and a hash for scripts, describe what
'strict-dynamic'changes, say why'unsafe-inline'is ignored next to a nonce, roll a policy out in report-only mode, and explain what CSP does and does not protect. A TypeScript model of the specification's matching rules lets you check each prediction.
Think of the mail room of an office building. One rule is a list of approved senders: a parcel is delivered if the sender is on the list. Another is a sticker the building prints fresh every morning: a parcel is delivered only if it carries today's sticker. The first rule fails when an approved sender ships something it should not, or when a stranger finds a way to ship through an approved sender. The second fails only if someone steals today's sticker.
A browser applying a CSP is that mail room: the server sends a rule with the response, and the browser applies it to everything the page then loads or runs. The rule can name approved senders (an allowlist of origins) or ask for a fresh proof on every script (a nonce or a hash). Most of this lesson is about why the second holds up better.
The running example is a shop's product page at https://shop.example. It loads its own bundle, a chart library from https://cdn.shop.example, images from https://img.shop.example and data from https://api.shop.example, and it has a small inline script that boots the page with the signed-in user's id. (The .example names are reserved for documentation.) The question: if an attacker gets one line of their own markup into that page, what stops it running?
The core idea
- A CSP is a rule the browser enforces after the response arrives. It limits where the page may load resources from and whether inline code may run. MDN describes the main use as controlling which resources, "in particular JavaScript resources", a document may load, mainly as a defence against cross-site scripting (XSS).
- A CSP limits the damage of an injection; it does not prevent the injection. OWASP calls it "an effective second layer of protection" that "should not be relied upon as the only defensive mechanism against XSS". Output encoding and safe APIs stay the first layer. (The lesson on XSS defenses in this course is planned and has no page yet.)
- Trust is given by origin or by proof. An allowlist trusts every script an origin serves. A nonce or hash trusts one specific script. web.dev recommends the proof-based form, a strict CSP, and says allowlist policies "require a lot of customization" and can be bypassed.
This lesson follows the W3C Content Security Policy Level 3 draft (the specification), MDN, web.dev and OWASP. It builds on The Same-Origin Policy and CORS: that policy decides what a page may read from another origin; CSP decides what it may load and run.
How a policy reaches the page
The server sends a CSP in a response header, and MDN says it should be on all responses, "not just the main document". A policy can also go in a meta element, which MDN calls useful for something like a client-rendered app with only static resources, but "this option does not support all CSP features": the specification lists report-uri, frame-ancestors and sandbox as unsupported there.
- Report-only mode. The
Content-Security-Policy-Report-Onlyheader evaluates a policy and reports violations without blocking anything. It cannot be used in ametaelement, and MDN sayssandboxis ignored in it. It needsreport-to(or the deprecatedreport-uri) to be useful. - Several policies at once. The browser enforces each policy it receives. The specification's non-normative note says a request "would have to pass through both unscathed": adding a policy can only restrict further. A report-only policy runs beside an enforced one without affecting it.
Figure 1. A policy travels with the response and is checked on every load
How to read this: the browser, not the server, applies the rule. Every script, image and connection the page starts is compared with the policy. What does not match is blocked (or, in report-only mode, only reported).
Anatomy of a policy
A policy is a string of directives separated by semicolons. A directive is a name followed by whitespace-separated values, usually a source list. Directive names are case-insensitive, a repeated directive is ignored (the first one counts), and empty segments are skipped.
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.shop.example; img-src 'self' https://img.shop.example; connect-src 'self' https://api.shop.example
| Expression | What it matches | Notes |
|---|---|---|
'self' |
The page's own origin | Quotes are part of the keyword. Never matches a blob: URL |
'none' |
Nothing | Only meaningful alone; next to other sources it has no effect |
cdn.shop.example |
That host | A scheme such as https:// is optional; with none, the page's scheme is used, and an insecure scheme may match its secure upgrade, never the reverse |
*.shop.example |
Any subdomain | Does not match the bare shop.example |
https: |
Every URL with that scheme | One token trusts a whole scheme |
'nonce-...' |
An element whose nonce attribute is identical |
Case-sensitive, exact |
'sha256-...' |
An inline block with that hash | sha256, sha384 or sha512 |
'strict-dynamic' |
Scripts added by an already-trusted script | Replaces origin matching for scripts |
'unsafe-inline', 'unsafe-eval' |
Inline code, eval() |
The names are the warning |
A host source can also carry a port (:8443, :*) and a path. A path ending in / matches everything below it by whole segments; otherwise it must match exactly. The specification checks the path only before any redirect, so after a redirect only the host side is checked.
Fetch directives and their fallbacks
Each fetch directive controls one kind of load: script-src, style-src, img-src, font-src, frame-src, object-src, connect-src (where script may connect with fetch(), XMLHttpRequest, WebSocket, EventSource and navigator.sendBeacon(), per MDN), and others. default-src is the fallback: "for each of the following directives that are absent, the user agent looks for the default-src directive" (MDN). For scripts the specification's chain is script-src-elem, then script-src, then default-src; script-src-attr governs inline event handlers.
Figure 2. Which directive decides for a script element
in the policy?"} B -->|"yes"| X["Use it"] B -->|"no"| C{"script-src
in the policy?"} C -->|"yes"| X C -->|"no"| D{"default-src
in the policy?"} D -->|"yes"| X D -->|"no"| E["No directive applies:
the script is allowed"]
How to read this: a policy with none of the three says nothing about scripts, so scripts are unrestricted. Images (img-src, then default-src) and the other fetch directives work the same way.
Three directives do not use default-src. MDN's list of what it covers excludes base-uri and form-action, and the specification and MDN say frame-ancestors does not fall back: "A policy that declares default-src 'none' still allows the resource to be embedded by anyone."
What a policy blocks by default
Once a policy has default-src or script-src, MDN says inline JavaScript "will not be allowed to execute unless extra measures are taken": inline script elements, event handler attributes such as onclick, and javascript: URLs. So are eval(), the Function() constructor and string arguments to setTimeout(), unless 'unsafe-eval' is present. style-src does the same for inline style elements and attributes, which MDN calls "one of the biggest security wins CSP provides". Setting element.style.display from script is not blocked.
This is the point of the feature: the usual XSS payload is an inline script or an event handler such as onerror, and with no way to run inline code, injected markup is inert. It is also the cost: legitimate inline code, such as the shop's boot script, must move to a file or get a nonce or hash.
Why allowlists age badly
The obvious first policy trusts the hosts the page uses: script-src 'self' https://cdn.shop.example. It reads well and fails in a specific way: it trusts every script those hosts will ever serve, including any a visitor can influence and any outdated file left on the CDN. A host source ignores paths the policy does not list, a redirect hides the path completely, and a scheme source such as https: trusts the whole web.
web.dev says a policy like script-src www.googleapis.com is "probably not effective against cross-site" scripting, and OWASP says a non-strict policy "that is too granular or permissive is likely to lead to bypasses". The structural problem is enough: an allowlist answers "where did this come from?", and the attacker asks "what can I make that place serve?".
Nonces and hashes: trust one script
A nonce is a random value the server generates for each response. The policy carries it, and every script the server intends to run carries the same value.
Content-Security-Policy: script-src 'nonce-r4nd0m1'; object-src 'none'; base-uri 'none'
<script nonce="r4nd0m1">window.__BOOT__ = { user: 42 };</script>
MDN: "the nonce must be different for every HTTP response, and must not be predictable". web.dev adds cryptographically strong and Base64 encoded:
import { randomBytes } from "node:crypto";
const newNonce = () => randomBytes(16).toString("base64"); // a new value for every response
The browser compares the element's nonce attribute with the policy's nonce-source, string for string. An attacker who injects markup cannot know the value for this response, so an injected script is blocked. The specification also hides the attribute from the page, moving it into an internal slot so that CSS selectors cannot read it out.
Figure 3. A nonce-based page and an injected script
(own script carries the nonce) B->>B: own script: nonce matches, run Note over B: an injected script has no nonce B->>B: injected script: no match, block B-->>R: violation report
How to read this: the proof is created per response by the server that knows which scripts are its own. Markup injected later cannot copy it.
Two rules follow. The nonce must be added by the template that renders the page, not by a layer that rewrites any script tag it finds: OWASP warns that "attacker-injected scripts will then get the nonces as well". And the nonce is per response, so HTML cannot be cached and shared while its header changes (the scenario below). A page that must be static uses hashes.
A hash trusts a script by its content: the policy carries the base64 digest of the exact text between the tags.
Content-Security-Policy: script-src 'sha256-FXgRORytp153QNxYNMYSBwu8U0gu+Qn8s6X7VZCpLMU='
That digest is the SHA-256 of window.__BOOT__ = { user: 42 } exactly as written, with no semicolon; the lab prints it in scenario 4. The specification hashes the UTF-8 bytes of the text and accepts sha256, sha384 and sha512. MDN warns that "capitalization and whitespace matter, including leading or trailing whitespace": one extra space changes the hash. For an external script the hash is checked against its integrity attribute, which must be present. Hashes suit static pages. They do not apply to event handler attributes except through 'unsafe-hashes'.
'strict-dynamic': trust that spreads
Real pages load scripts that load scripts: a bundle that imports a chart library, a tag loader that adds an analytics script. With a plain nonce policy each of those needs its own nonce, which the loader cannot know. MDN: 'strict-dynamic' "specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. At the same time, any allowlist or source expressions such as 'self' or 'unsafe-inline' will be ignored."
The specification's script check is a short ordered list: allow if the nonce matches; allow if an integrity hash is listed; if the list has 'strict-dynamic', block a parser-inserted script (written in the HTML) and allow any other (created by a script, for example with createElement); otherwise match the URL against the source list.
Figure 4. How a script request is decided
listed?"} C -->|"yes"| OK C -->|"no"| D{"'strict-dynamic'
in the list?"} D -->|"yes"| E{"Inserted by
the parser?"} E -->|"yes"| X["Block"] E -->|"no"| OK D -->|"no"| F{"URL matches
a source?"} F -->|"yes"| OK F -->|"no"| X
How to read this: with 'strict-dynamic' the URL is never looked at. A script written in the markup needs a nonce or hash; a script added by a trusted script is trusted too, wherever it comes from.
That last point is also the risk: the specification says to audit uses of non-parser-inserted APIs, because if an attacker controls where a trusted script loads its next script from, the policy permits it. MDN says the keyword "does make your CSP less secure". Scripts from document.write are parser-inserted, so they are blocked.
web.dev's recommended shape:
Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none';
object-src 'none' blocks plugin content; base-uri 'none' stops an injected base element from changing where relative script URLs resolve. For old browsers web.dev adds 'unsafe-inline' and https: after the nonce: "all recent browsers ignore unsafe-inline if a CSP nonce or hash is present", and https: is ignored where 'strict-dynamic' is understood.
The 'unsafe-inline' trap
'unsafe-inline' allows every inline script and handler, but the specification's inline check counts it only if the source list has no nonce-source and no hash-source. So script-src 'unsafe-inline' 'nonce-r4nd0m1' still blocks an injected inline script, which surprises people who kept it as a safety net. The reverse is worse: 'unsafe-inline' with no nonce or hash lets every injected inline script run. MDN's advice is to avoid 'unsafe-inline' and 'unsafe-eval'.
Beyond scripts
object-src 'none'andbase-uri 'none', as above;base-urihas nodefault-srcfallback.frame-ancestorscontrols who may embed your page. It checks every ancestor, does not fall back and is ignored inmeta.'none'is similar toX-Frame-Options: deny(MDN), and OWASP says it makes that header obsolete. It is the CSP side of clickjacking defence, which has its own lesson later in this course.form-actionrestricts where forms may submit, so an injected form cannot post to another site.connect-srclimits where script can send data, which makes it harder for injected code to send out what it reads.
Trusted Types targets DOM XSS, where a script writes untrusted text into a sink such as innerHTML. With require-trusted-types-for 'script', assigning a plain string to a sink throws, because "the browser doesn't know if the data is trustworthy"; code passes data through a policy, a factory that applies a rule such as escaping. web.dev's page lists Chrome and Edge 83, Firefox 148 and Safari 26 at the time of writing; check current support first.
Rolling out: report first, enforce later
A strict CSP breaks pages that rely on inline code, and the breakage is easier to find before enforcement. web.dev's adoption steps: pick nonce or hash, set the header on every response, refactor incompatible templates and client code, and deploy, optionally starting in report-only mode. OWASP calls report-only "non-blocking" ("fail open") and "often used as a precursor to utilizing CSP in blocking mode", and says a strict report-only policy can run beside a looser enforced one.
Reports go to an endpoint named by report-to, which refers to a name defined in the Reporting-Endpoints header. OWASP calls report-to current and report-uri deprecated by CSP Level 3, and advises declaring both. MDN says report-to must be specified for reports to be sent, otherwise "the operation won't have any effect".
Reporting-Endpoints: csp-endpoint="https://shop.example/csp-reports"
Content-Security-Policy-Report-Only: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; report-to csp-endpoint
What CSP does not do. It blocks the execution of injected script and limits some follow-on damage. It does not stop HTML injection, does not protect against a trusted script that is itself malicious, and does not authenticate anyone. The browser alone enforces it, so curl ignores it.
Three illustrations
Illustration 1 (minimal). A comment field stores <img src=x onerror="steal()"> and the page renders it unescaped. With no CSP the handler runs. With Content-Security-Policy: script-src 'self', inline handlers are not allowed, so onerror does not run. The bug is still there; its consequence is smaller.
Illustration 2 (realistic). The shop's product page, with a strict policy:
Content-Security-Policy: script-src 'nonce-{RANDOM}' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; img-src 'self' https://img.shop.example; connect-src 'self' https://api.shop.example; form-action 'self'
The server puts the same fresh nonce on the bundle and the boot script. The bundle may add the chart library from anywhere, because trust spreads from it, so a new CDN needs no policy change, and an injected script tag or onerror attribute does not run. The injection itself is not stopped; img-src and connect-src narrow where injected markup can send requests.
Illustration 3 (failure). The page's HTML is cached at the CDN for ten minutes (illustrative) but the header's nonce is generated per request. The cached HTML carries the nonce of the request that filled the cache, later requests get a different nonce in the header, and no script runs. The quiet inverse is a nonce hard-coded in a template: any injected script that learns it once can run forever. Both treat the nonce as configuration instead of a per-response value.
Choosing an approach
Figure 5. Which trust mechanism for which page
per response?"} -->|"yes"| N["Nonce + 'strict-dynamic'"] A -->|"no, static or cached"| H["Hashes for inline scripts,
integrity on external ones"] N --> R["Start in report-only,
then enforce"] H --> R A -.->|"cannot refactor yet"| L["Allowlist as a temporary step,
not as the goal"]
How to read this: the page's delivery model decides the proof mechanism. An allowlist is the fallback when the page cannot be refactored yet; it is a step, not the end.
| Approach | Gain | Cost | Weakness |
|---|---|---|---|
| Origin allowlist | Easy to write; no template change | A list to maintain | Trusts everything those hosts serve |
Nonce + 'strict-dynamic' |
No host list; trust spreads | Fresh nonce per response; HTML not shareable between users | Trusted scripts spread trust |
| Hashes | Static policy for static pages | Changes with any edit; needs a build step | No event handlers without 'unsafe-hashes' |
'unsafe-inline' |
No refactoring | None up front | Allows every injected inline script |
| Report-only first | Finds breakage safely | An endpoint to run and read | Blocks nothing while it runs |
The other side of this topic
On the server side the policy is a header some layer must write on every response: the application, the gateway or the CDN. Which layer owns it decides who can add a nonce, and whether cached HTML can carry one. The front-end skill is knowing which pages are rendered per response and which are static, because that decides which mechanism is possible.
Build it: evaluate a policy against a page
Goal. Parse a policy string and decide, for the page https://shop.example/products, whether it lets a script, style, image, connection, frame or inline block through, with the reason. Then lint four policies.
Setup. The lab lives in the course's example workspace. It needs Node.js (captured on Node 26.13.1, which runs the TypeScript files directly) and pnpm. It has no browser and no network: it models the matching rules of the specification.
cd examples/frontend
pnpm install
pnpm --filter ./labs/csp-evaluator test # 81 tests
cd labs/csp-evaluator
node src/demo.ts
Steps.
- In scenario 2 (an allowlist policy) predict which lines are blocked before reading the verdicts. The inline script, the handler and
evalare blocked although no directive mentions them. - In scenario 3, find the scripts that differ only in how they are inserted. The one with the nonce and the one added by a script are allowed. The two in the markup without a nonce are blocked, even the one from the page's own origin: with
'strict-dynamic'the listed sources are ignored. - In scenario 5, compare the two
'unsafe-inline'policies: adding a nonce turns'unsafe-inline'off. - In scenario 6, find
base-uri,form-actionandframe-ancestors: withdefault-src 'none'they are still allowed. - In scenario 7, a report-only policy leaves the verdict alone but adds a report; enforced, the same policy blocks.
The core is the script check from Figure 4:
if (nonceMatches(list, request.nonce)) return allow("nonce matches");
if (integrityMatches(list, request.integrity ?? [])) return allow("integrity hash is listed");
if (hasKeyword(list, "strict-dynamic")) {
return request.parserInserted === true
? block("'strict-dynamic': a parser-inserted script needs a matching nonce or integrity hash")
: allow("'strict-dynamic': inserted by a script that was trusted, so the URL is not checked");
}
return matchesSourceList(list, new URL(request.url), page) ? allow("URL matches a source expression") : block("URL matches no source expression");
Expected output, captured from a real run (Node 26.13.1, 2026-12-01):
Content Security Policy evaluator: the page is https://shop.example/products
=== 1. Parsing: names fold to lower case, the first duplicate wins
serialized: default-src 'self'; script-src 'self' https://cdn.shop.example
ignored: script-src (duplicate), img_src (invalid-name)
in a meta element: kept [default-src], ignored [frame-ancestors, report-uri]
=== 2. An allowlist policy: hosts are trusted, inline code is not
policy: default-src 'self'; script-src 'self' https://cdn.shop.example; img-src 'self' https://img.shop.example; connect-src 'self' https://api.shop.example
allow script https://shop.example/assets/app.js
script-src: URL matches a source expression
allow script https://cdn.shop.example/chart.js
script-src: URL matches a source expression
BLOCK script https://evil.example/steal.js
script-src: URL matches no source expression
BLOCK inline script "window.cart = []"
script-src: inline code needs a nonce, a matching hash, or 'unsafe-inline' without any nonce or hash in the list
BLOCK inline handler onclick="buy()"
script-src: inline event handlers need 'unsafe-hashes' with a matching hash, or 'unsafe-inline' without any nonce or hash
BLOCK eval("1 + 1")
script-src: eval() and similar need 'unsafe-eval'
allow img https://img.shop.example/p/1.png
img-src: URL matches a source expression
BLOCK img https://evil.example/pixel.gif
img-src: URL matches no source expression
allow connect https://api.shop.example/v1/cart
connect-src: URL matches a source expression
BLOCK connect https://evil.example/collect
connect-src: URL matches no source expression
BLOCK frame https://pay.example/checkout
default-src: URL matches no source expression
=== 3. A strict policy: a nonce, 'strict-dynamic', no host list
policy: script-src 'nonce-r4nd0m1' 'strict-dynamic' https://ignored.example 'self'; object-src 'none'; base-uri 'none'
allow inline script "window.__BOOT__ = { user: 42 }" nonce=r4nd0m1
script-src: nonce matches
BLOCK inline script "document.title = 'injected'"
script-src: inline code needs a nonce, a matching hash, or 'unsafe-inline' without any nonce or hash in the list
BLOCK inline script "window.__BOOT__ = { user: 42 }" nonce=guess123
script-src: inline code needs a nonce, a matching hash, or 'unsafe-inline' without any nonce or hash in the list
allow script https://shop.example/assets/app.js nonce=r4nd0m1 (in the markup)
script-src: nonce matches
BLOCK script https://shop.example/assets/other.js (in the markup)
script-src: 'strict-dynamic': a parser-inserted script needs a matching nonce or integrity hash
BLOCK script https://ignored.example/lib.js (in the markup)
script-src: 'strict-dynamic': a parser-inserted script needs a matching nonce or integrity hash
allow script https://cdn.third-party.example/widget.js (added by a script)
script-src: 'strict-dynamic': inserted by a script that was trusted, so the URL is not checked
BLOCK inline handler onclick="buy()"
script-src: inline event handlers need 'unsafe-hashes' with a matching hash, or 'unsafe-inline' without any nonce or hash
BLOCK object https://shop.example/legacy.swf
object-src: URL matches no source expression
BLOCK base-uri https://evil.example/
base-uri: URL matches no source expression
=== 4. The same inline script allowed by its hash (change one character and it is blocked)
policy: script-src 'sha256-FXgRORytp153QNxYNMYSBwu8U0gu+Qn8s6X7VZCpLMU='
allow inline script "window.__BOOT__ = { user: 42 }"
script-src: sha256 hash of the text matches
BLOCK inline script "window.__BOOT__ = { user: 42 } "
script-src: inline code needs a nonce, a matching hash, or 'unsafe-inline' without any nonce or hash in the list
=== 5. The 'unsafe-inline' trap: it is ignored once a nonce is listed
policy: script-src 'unsafe-inline'
allow inline script "injected()"
script-src: 'unsafe-inline' allows all inline code (no nonce or hash in the list)
policy: script-src 'unsafe-inline' 'nonce-r4nd0m1'
BLOCK inline script "injected()"
script-src: inline code needs a nonce, a matching hash, or 'unsafe-inline' without any nonce or hash in the list
allow inline script "boot()" nonce=r4nd0m1
script-src: nonce matches
=== 6. Fallbacks: default-src covers fetches, not base-uri, form-action or frame-ancestors
policy: default-src 'none'; img-src 'self'
allow img https://shop.example/logo.png
img-src: URL matches a source expression
BLOCK font https://shop.example/inter.woff2
default-src: URL matches no source expression
allow base-uri https://evil.example/
(none): no directive applies, so nothing is restricted
allow form-action https://evil.example/steal
(none): no directive applies, so nothing is restricted
allow framed by https://evil.example/
(none): no directive applies, so nothing is restricted
policy: default-src 'none'; frame-ancestors 'self'; form-action 'self'
BLOCK framed by https://evil.example/
frame-ancestors: ancestor https://evil.example/ matches no source expression
allow form-action https://shop.example/checkout
form-action: URL matches a source expression
=== 7. Two policies and a report-only trial of a stricter one
allowed script https://shop.example/assets/app.js
blocked by policies: [] violation reports from report-only: []
allowed script https://cdn.shop.example/chart.js
blocked by policies: [] violation reports from report-only: [1]
BLOCKED script https://evil.example/steal.js
blocked by policies: [0] violation reports from report-only: [1]
with the second policy enforced instead: BLOCKED (blocked by [1])
=== 8. The linter
a policy that looks like a CSP: default-src 'self' 'unsafe-inline' 'unsafe-eval' https: *.shop.example
high unsafe-inline [default-src]: 'unsafe-inline' lets any injected inline script or handler run
medium unsafe-eval [default-src]: 'unsafe-eval' lets eval(), Function() and string timers run
high scheme-source [default-src]: https: matches every URL with that scheme
medium host-allowlist [default-src]: *.shop.example: an allowlist trusts every script that host can serve, including any a visitor can influence
medium style-unsafe-inline [default-src]: 'unsafe-inline' allows every inline style element and style attribute
medium no-base-uri: no base-uri (it does not fall back to default-src): an injected base element can redirect relative script URLs
info no-frame-ancestors: no frame-ancestors (it does not fall back to default-src): any site may frame the page
an allowlist policy: script-src 'self' https://cdn.shop.example; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
medium host-allowlist [script-src]: https://cdn.shop.example: an allowlist trusts every script that host can serve, including any a visitor can influence
a strict policy with old-browser fallbacks: script-src 'nonce-r4nd0m1' 'strict-dynamic' 'unsafe-inline' https:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
info unsafe-inline-ignored [script-src]: 'unsafe-inline' is ignored by browsers that support nonces or hashes, because a nonce or hash is present
info scheme-source-ignored [script-src]: https: is ignored where 'strict-dynamic' is supported (a fallback for older browsers)
the strict policy as a report-only trial: script-src 'nonce-r4nd0m1' 'strict-dynamic'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'
info report-only: this policy only reports violations; it blocks nothing
medium no-reporting: report-only without report-to or report-uri: there is nowhere to send the reports
=== 9. A nonce must be new for every response
nonces seen in more than one response: aaa111
What the lab does not show. It models the specification's rules, not a browser: it loads nothing, sends no report and says nothing about what any browser supports. It skips redirect counting, child-src, worker-src, Trusted Types, 'wasm-unsafe-eval', 'report-sample' and inline style attributes. The linter reflects the guidance cited here; it can find a weak policy and cannot prove a strong one.
Break it. In src/sources.ts, in allowsAllInline, delete the line if (NONCE_SOURCE.test(token) || HASH_SOURCE.test(token)) return false;. The injected inline script in scenario 5 is now allowed next to a nonce, and two tests fail. Put the line back.
Stretch. Add child-src and worker-src to the fallback chains, or carry a redirect count and skip the path check after the first redirect, as the specification does.
In practice: moving a product page from an allowlist to a strict policy
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.
The situation
The shop's product page is rendered per request. Its CSP is an allowlist: script-src 'self' 'unsafe-inline' https://cdn.shop.example https://tags.example.net. The 'unsafe-inline' is there for a boot script and a few onclick attributes, so the policy would not stop an injected inline script. A security review asks for a strict policy. Three teams add scripts: the shop team, a payments widget team and a marketing team that uses a tag loader.
Starting architecture
Figure 6. Starting point: an allowlist that also allows inline code
How to read this: the warning boxes are where the policy is weak. Inline code runs everywhere because of 'unsafe-inline', and everything the tag loader serves is trusted.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
Allowlist without 'unsafe-inline' |
Injected inline script blocked | Boot script and handlers must go | Allowlisted hosts still fully trusted |
Nonce + 'strict-dynamic' |
No host list; children inherit trust | A nonce per response; HTML caching needs a plan | A trusted script that loads from an attacker-influenced place |
| Hashes | Works for static pages | Rebuild on every edit | The page is dynamic, so hashes rarely match |
The decision
| Field | Decision record |
|---|---|
| Context | A per-request page with an allowlist and 'unsafe-inline'; three teams add scripts. |
| Decision | Nonce plus 'strict-dynamic', with object-src 'none', base-uri 'none' and frame-ancestors 'none'. Run it as report-only beside the old policy first. Replace onclick attributes with addEventListener. The template adds the nonce. |
| Consequences, good | Injected inline script is blocked; new script hosts need no policy change. |
| Consequences, bad | The page HTML must not be shared between users from a cache; scripts that call document.write stop working. |
| Revisit when | Reports show a trusted script loading from where it should not, or the page becomes static (use hashes). |
Rollout and verification
- Add the report-only policy with
report-to, next to the old enforced one, on every response. - Read the reports for a full release cycle, grouped by directive and blocked URL, and fix the templates and handlers they point at.
- Check the nonce path: the page source and the response header carry the same value, and two requests get two different values.
- Enforce by moving the policy to
Content-Security-Policy, and keep the report endpoint.
The 2 a.m. failure
An hour after enforcement, payments reports that the checkout widget does not load for some shoppers, and violation reports spike on script-src. Page views are normal.
The cause is caching. A performance change that week let the CDN cache the product page's HTML for a few minutes (illustrative), but the nonce header is generated per request and is not what is cached. The cached HTML contains the nonce of the request that filled the cache, so later shoppers get a header with a different nonce, no script in the markup matches and, with 'strict-dynamic', nothing can start.
First three checks: (1) compare the nonce in the failing page's source with the one in its response header; (2) request the URL twice and see which values change; (3) check the CDN's cache status for the HTML. Mitigation: switch the policy back to report-only and stop caching the HTML (or cache a shell and add the nonce at the edge). Follow-up: a test that fetches the page twice and asserts the nonces match within each response and differ between responses, and an alert on the rate of script-src reports.
Architect's notes
- Start strict on new pages and migrate old ones; avoiding inline code is cheaper than removing it.
- Decide who owns the header. Two writers produce two policies, and the browser enforces both.
- Treat the nonce as a per-response secret, rendered by the template and absent from cached HTML.
- Use CSP so the next injection is small, not instead of fixing it, and watch the reports: a rising count is an attack, a regression or a broken release.
Common mistakes
- Keeping
'unsafe-inline'"for now". Without a nonce or hash it allows every injected inline script. - Caching HTML that contains a nonce, or hard-coding a nonce in a template.
- Relying on
default-srcforbase-uri,form-actionandframe-ancestors. They do not fall back. - Putting
frame-ancestors,report-uriorsandboxin ametaelement. They are ignored there. - Allowlisting a CDN for scripts. You trust everything it serves.
- Enforcing with no report-only phase.
Key takeaways
- A CSP is a response header the browser enforces on every load; send it on all responses.
- Fetch directives fall back through
script-src-elem,script-src,default-src;base-uri,form-actionandframe-ancestorsdo not usedefault-src. - With a policy in place, inline scripts, event handler attributes,
javascript:URLs andeval()are blocked unless allowed on purpose. - Allowlists trust whole origins; nonces and hashes trust single scripts.
- A nonce is new and unpredictable for every response; a hash covers exact text, whitespace included.
'strict-dynamic'spreads trust from a nonced or hashed script to the scripts it adds, and ignores host lists and'self'.'unsafe-inline'is ignored when a nonce or hash is present; without one it allows all inline code.- Roll out with
Content-Security-Policy-Report-Onlyandreport-to; CSP is a second layer, not a fix for injection.
Practice exercises
Exercise 1 — Starter (30 min): For https://shop.example/products, write a policy that allows scripts only from the page's own origin and images from one image host. In the lab, predict then check six requests: an own script, an inline script, an image from the listed host, an image from another host, an inline handler and eval.
Exercise 2 — Intermediate (2 hours): Convert the allowlist policy in scenario 2 to a nonce policy with 'strict-dynamic'. List which scripts need a nonce and which are added by other scripts, and confirm in the lab that a script added by a script is allowed while the same URL in the markup is not.
Exercise 3 — Advanced (half day): Lint the policy of a site you maintain. Decide for each finding whether it is a real weakness, a documented fallback or a limit of the linter, then design the report-only rollout: where reports go, who reads them and what makes you enforce.
Related reading
In this course:
- The Same-Origin Policy and CORS, what a page may read from another origin, the layer under CSP.
- The planned lessons on XSS defenses, CSRF and clickjacking defenses, and token storage cover the neighbouring parts of front-end security; they have no pages yet.
Elsewhere on the site:
- System Design: Security, the server-side defences CSP does not replace.
Official documentation
- W3C: Content Security Policy Level 3, the grammar, the matching algorithms and the script check.
- MDN: Content Security Policy (CSP),
script-srcanddefault-src. - MDN:
Content-Security-Policy-Report-Only. - web.dev: Mitigate XSS with a strict Content Security Policy and Trusted Types.
- OWASP: Content Security Policy Cheat Sheet.