Lesson 4 · The web platform, in depth
Front-end security: XSS and CSP
How injection attacks work in the browser and the defenses that stop them.
About 30 minutes
Tab indents. Press Escape, then Tab, to leave the editor.
Cross-site scripting (XSS) means an attacker's data gets executed as script in your origin. Once it runs, it is your code as far as the browser is concerned: it can read the DOM, call your APIs with the user's cookies, read any token in localStorage, rewrite the page into a phishing form, and persist itself. This lesson treats XSS as a data-flow problem (sources reaching sinks), then layers the defenses: safe DOM APIs, sanitization, Trusted Types, Content Security Policy, and cookie attributes that limit the damage.
Sources, sinks and the three flavors
- Stored XSS: the payload is saved server-side (a comment, a profile name) and served to every viewer.
- Reflected XSS: the payload comes in the request (a query parameter) and the server echoes it into the HTML.
- DOM-based XSS: the server never sees it. Client code reads attacker-controllable data and writes it into a dangerous API. Single-page apps shift most risk here.
DOM XSS is easiest to reason about as sources flowing into sinks:
| Sources (attacker can influence) | Sinks (interpret strings as code or markup) |
|---|---|
location.hash, location.search, location.href | innerHTML, outerHTML, insertAdjacentHTML, document.write |
document.referrer, window.name | eval, new Function, setTimeout('string') |
postMessage event data | script.src, script.text, iframe.srcdoc |
localStorage, IndexedDB (if anything else can write them) | a.href, location.href, form.action with javascript: URLs |
| API responses containing user content | Framework escape hatches: React's dangerouslySetInnerHTML, Vue's v-html, Angular's bypassSecurityTrust* |
A detail that misleads people: <script> elements inserted with innerHTML don't execute. That's not a defense, because event handler attributes do. <img src=x onerror="…"> runs as soon as the image fails to load, and that happens even if the element was never attached to the document.
Fix it at the sink
The robust fix is to never hand user data to an HTML parser. Build the structure with DOM APIs and insert user data as text:
const li = document.createElement('li')
const name = document.createElement('strong')
name.textContent = comment.author // text, never parsed as markup
li.append(name, ': ', comment.text) // strings passed to append() become text nodes
Frameworks do this for you in the normal path. React and Vue escape text children and attribute values, which is why most XSS in framework apps comes through the escape hatches in the table above, or through URL attributes. Escaping doesn't help with URLs: href={user.website} is perfectly escaped and still runs javascript:alert(1) when clicked. Parse the URL and allowlist the scheme:
function safeHttpUrl(value) {
try {
const url = new URL(value, document.baseURI)
return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : null
} catch {
return null
}
}
new URL() normalizes the tricks that defeat string checks: leading whitespace and control characters, mixed case (JaVaScRiPt:), and embedded tabs and newlines are all handled the way the browser itself will interpret them.
Challenge
Fix the comment renderer
renderComment(list, comment) builds a comment from { author, text, website? }. It uses innerHTML with user data, and one of the seeded comments proves it: the status line says injected script ran.
Rewrite renderComment so that:
- author and text are always shown literally, never parsed as HTML,
- the author is still wrapped in
<strong>, - a website link is only rendered for
http:orhttps:URLs.
Don't just escape < and > by hand: build DOM nodes.
- Nothing logged yet.
- Markup in the comment text is shown as text and never runs
- Markup in the author name is shown as text, still inside <strong>
- javascript: URLs never become links, but https: URLs still do
When you genuinely need HTML: sanitize
Rendering user-authored rich text (Markdown output, pasted HTML) means parsing markup on purpose. Then sanitize with an allowlist parser that runs in the browser's own HTML parser, such as DOMPurify, immediately before the sink. Don't write regex sanitizers: HTML parsing has too many quirks (mutation XSS exploits the difference between how a sanitizer parsed a string and how the browser re-parses its output). The standard HTML Sanitizer API (element.setHTML(input)) is designed for exactly this. Firefox 148 shipped it in February 2026 and Chrome and Edge list support from version 146, but Safari doesn't support it yet, so feature-detect it ('setHTML' in Element.prototype) and fall back to a library.
Sanitize at output, close to the sink, not at input. Data stored "already sanitized" for one context (HTML) is still dangerous in another (a URL, a JavaScript string, a CSS value), and sanitizer rules improve over time.
Trusted Types: make the sinks refuse strings
Code review can't reliably find every innerHTML in a large app and its dependencies. Trusted Types moves the check into the browser. With this response header:
Content-Security-Policy: require-trusted-types-for 'script'; trusted-types comments
DOM XSS sinks throw a TypeError when given a plain string. They accept only TrustedHTML, TrustedScript or TrustedScriptURL objects, which can only be minted by a named policy you register:
const policy = trustedTypes.createPolicy('comments', {
createHTML: (input) => DOMPurify.sanitize(input),
})
preview.innerHTML = policy.createHTML(markdownOutput) // allowed
preview.innerHTML = markdownOutput // TypeError under enforcement
The security review shrinks to the policy functions, and the trusted-types directive limits which policy names may exist. Chromium has enforced Trusted Types since 2020 (Chrome 83); Safari 26 and Firefox 148 added it, making it Baseline in 2026. Older browsers ignore the header, so it's safe to deploy, and Content-Security-Policy-Report-Only lets you collect violations before enforcing.
Content Security Policy that actually stops XSS
CSP limits what can execute even after an injection succeeds. The design that holds up is a strict CSP based on nonces or hashes, not a list of allowed hosts. Host allowlists are routinely bypassed through endpoints on the allowed hosts: JSONP callbacks, or old library versions on a CDN with script gadgets.
Content-Security-Policy:
script-src 'nonce-r4nd0mBase64' 'strict-dynamic' https: 'unsafe-inline';
object-src 'none';
base-uri 'none';
'nonce-…': only<script nonce="r4nd0mBase64">elements run. The nonce must be unpredictable and regenerated for every response. An injected<script>lacks it, and inline event handlers (onerror=) are blocked outright, so the payload in the playground would have been stopped here too.'strict-dynamic': a script that's allowed may load further scripts by creating<script>elements, without you listing their hosts. In browsers that support it, host sources likehttps:and'self'are ignored. Parser-inserted scripts (document.write) don't inherit the trust.https:and'unsafe-inline'are fallbacks for browsers too old to understand nonces or'strict-dynamic'. Current browsers ignore them when a nonce or hash is present.object-src 'none'removes plugin content;base-uri 'none'stops an injected<base>tag from redirecting your relative script URLs.
Nonces need per-response HTML, which has a cost: a fully static, CDN-cached page can't carry a fresh nonce. In Next.js, for instance, reading a nonce makes the route render dynamically on every request. For static pages, use hashes ('sha256-…' of each inline script's content) instead. Add frame-ancestors 'none' (or a list of allowed parents) to stop clickjacking; it replaces the old X-Frame-Options header.
Cookies and CSRF: limit the blast radius
Session cookies should be set with:
Set-Cookie: __Host-session=…; Secure; HttpOnly; SameSite=Lax; Path=/
HttpOnly: JavaScript can't read the cookie, so XSS can't exfiltrate the session token. It can still use it: script running in your origin makes same-origin requests that carry the cookie. HttpOnly limits persistence after the XSS is fixed, not what the XSS can do now.Secure: only sent over HTTPS.__Host-prefix: the browser rejects the cookie unless it'sSecure, hasPath=/and has noDomain, so a sibling subdomain can't overwrite it.SameSite:Strictnever sends the cookie on cross-site requests;Laxsends it only on top-level navigations with safe methods (following a link), not on cross-site POSTs, iframes orfetch;None(which requiresSecure) always sends it. Chromium treats cookies without the attribute asLax, but other engines differ, so set it explicitly.
Cross-site request forgery (CSRF) is another site making the user's browser send an authenticated, state-changing request to you. SameSite=Lax or Strict stops the classic form-POST version. Two gaps remain: GET requests with side effects (don't have them), and same-site attackers, because SameSite is about the registrable domain, so evil.example.com is same-site with app.example.com. Defense in depth on state-changing endpoints: reject requests whose Origin header isn't yours, or use Fetch Metadata (Sec-Fetch-Site: cross-site → reject), and use anti-CSRF tokens if you must support old clients.
A token in localStorage with an Authorization header is immune to CSRF but fully readable by any XSS. An HttpOnly cookie is unreadable by XSS but needs CSRF defenses. Neither survives XSS in the sense that matters, which is why the first half of this lesson is the important half.
Other client-side habits
postMessage: always checkevent.originagainst an exact allowlist before usingevent.data, and pass an explicittargetOrigin(never'*'for sensitive data) when sending.- Third-party scripts run with your origin's full power. Pin them with Subresource Integrity (
integrity="sha384-…") where the file is static, or isolate them in a sandboxed iframe. - Don't build HTML strings anywhere, including in tests and email templates. Search the codebase for the sinks in the table; each one is either justified with sanitization or replaced.
Recap
- XSS is untrusted data reaching a sink that parses markup or code; trace sources to sinks, especially in client code.
- Insert user data with
textContentand DOM construction, validate URL schemes withnew URL(), and sanitize with a real parser only when you need HTML. - Trusted Types makes sinks reject strings, shrinking review to a few policy functions.
- A strict CSP (
'nonce-…'or hashes,'strict-dynamic',object-src 'none',base-uri 'none') stops most injected scripts from running; host allowlists don't. HttpOnly,Secure,__Host-andSameSitelimit what a stolen or forged request can do; verifyOriginorSec-Fetch-Siteon state-changing endpoints.
Finished this lesson?
Mark it complete to track your progress on this device.