Skip to content

    Frontend System Design

    Cross-Site Scripting (XSS) and Its Defenses

    Learn how cross-site scripting works, why the right encoding depends on where text lands, and how encoding, sanitizing and Trusted Types stop it, with a lab.

    By Published 17 min read

    • frontend-system-design
    • xss
    • browser-security
    • output-encoding
    Share

    Flagship lessonintermediateTypeScript labFrontend System Design

    Before this: The Same-Origin Policy and CORS

    What you'll learn: By the end of this lesson you will be able to explain what cross-site scripting (XSS) lets an attacker do and why the browser cannot tell the difference, trace untrusted text from a source to a sink, choose the right output encoding for six contexts (HTML body, quoted attribute, unquoted attribute, JavaScript string, URL parameter, whole URL), avoid the DOM sinks that parse markup, decide between encoding, sanitizing and plain text, describe what Trusted Types add, and explain why a content security policy and HttpOnly cookies are backups rather than the main defense. A small TypeScript lab lets you check each rule.

    Imagine a print shop that prints whatever customers hand over onto its own letterhead. One customer brings a note that reads, in the shop's own voice, "Tell the next customer to hand over their house keys." The printer does not read the note as an instruction, it just prints, and the next customer has every reason to obey genuine letterhead.

    A web page is the letterhead. When a site puts user text into a page without making sure the browser reads it as plain text, the browser runs some of it as instructions with the site's authority. That is cross-site scripting, or XSS. This lesson is defensive, and every payload is a textbook string that is built and compared, never run.

    The running example is a product page on https://shop.example with customer reviews, a "You searched for ..." line, a seller website link and a small inline script that hands the signed-in user's name to the page. Three illustrations run through the lesson: a minimal example (the search line), a realistic example (reviews with a little formatting allowed) and a failure example (the inline script, and a link that starts with javascript:).

    The core idea

    Hold on to three statements.

    1. XSS is an output problem: text crossed from "data" to "code". MDN says all XSS attacks depend on a site accepting input an attacker could have crafted and including it in a page without handling it safely. Fix it where the text is written, because only there do you know what kind of place it is.
    2. What is safe depends on the context. The same characters mean different things in an HTML body, an attribute, a JavaScript string and a URL, so one escape applied once at input cannot be right for all of them.
    3. A page script runs with the page's authority. The same-origin policy (see the Same-Origin Policy and CORS) protects a site from other origins. In XSS the attacker's script is in the site's origin, so the policy works as designed and gives no protection.

    What XSS is and what it can do

    MDN defines XSS as an attack in which an attacker gets a target site to execute malicious code as though it were part of the website, and says that code can access and change everything in the loaded page and in local storage, and make HTTP requests with the user's credentials. The attacker has subverted the same-origin policy.

    The three variants differ only in where the text travels.

    • Stored XSS: the text is saved (a review, a profile field) and served to every visitor. MDN calls this particularly severe.
    • Reflected XSS: the server echoes part of the request (a search term) into the response, so the victim must be led to a crafted link.
    • DOM-based XSS: the response is harmless, but the page's own script reads something the attacker controls (a URL parameter) and writes it through an API that interprets it as code.

    Figure 1. Untrusted text on its way to another visitor

    Text typed by one visitor is stored by the server and rendered in another visitor's page, where it runs with the site's authorityWriter to Shop server (submits text); Shop server to Database (saves); Database to Page (renders); Page to Reader (reads and clicks)THE READER'S BROWSERWriter: posts a reviewWriterposts a reviewShop server: stores and servesShop serverstores and servesDatabase: saved textDatabasesaved textPage: shop.examplePageshop.exampleReader: signed inReadersigned insubmits textsavesrendersreads and clicks

    How to read this: nothing in the path is a "script upload". The text is ordinary data until the page writes it somewhere the browser interprets, and from then on it acts as the signed-in reader on the shop's own origin.

    Figure 2. A stored payload reaching the reader

    sequenceDiagram accTitle: Stored cross-site scripting in four steps accDescr: A writer submits a review that contains markup. The server stores it without encoding. A reader opens the product page. The server inserts the stored text into the HTML, the reader's browser parses it as markup and runs the script with the shop's authority. participant W as Writer participant S as Shop server participant R as Reader's browser W->>S: submit review (contains markup) S->>S: store the text as written R->>S: open the product page S-->>R: HTML with the review inserted as markup Note over R: the parser reads the review as tags R->>R: script runs as shop.example

    How to read this: the server never ran anything. The fault is the step where the stored text was placed into HTML as if it were markup. Encoding at that step turns the same text into harmless characters.

    Sources and sinks

    Every XSS bug is a path from a source, a place untrusted text enters (a form field, a URL, a stored record, a message from another window), to a sink, a place that interprets text as something executable. MDN's Trusted Types page names the sinks: HTML sinks such as Element.innerHTML and document.write(), JavaScript sinks such as eval(), and JavaScript URL sinks such as a script element's src.

    Sink What it does with the text Safer alternative
    innerHTML, outerHTML, document.write() Parses it as HTML textContent for plain text; a sanitizer plus Trusted Types if markup is required
    eval(), new Function(), setTimeout("...") Runs it as JavaScript A function value instead of a string; JSON.parse for data
    An event-handler attribute set from a string Runs it as JavaScript Attach a function with addEventListener
    href, src attributes Treats it as a URL, and a javascript: URL runs code An allow-list of schemes (see below)
    <script> or <style> content Runs or applies it Do not put untrusted text there at all

    Figure 3. Sources, the page's code and sinks

    The page's own script can carry untrusted text from a source to a dangerous sink or to a safe oneURL and hash to Page script; API response to Page script; Page script to Parsing sinks (text is interpreted); Page script to Safe sinks (text stays text)URL and hash: sourceURL and hashsourceAPI response: sourceAPI responsesourcePage script: reads, builds stringsPage scriptreads, buildsstringsParsing sinks: innerHTML, evalParsing sinksinnerHTML, evalSafe sinks: textContentSafe sinkstextContenttext is interpretedtext stays text

    How to read this: the route from source to sink is just the page's own code. Review a page by finding every sink and asking where its text came from.

    One text, six contexts

    Here is the minimal example. The page prints the search term: <p>Hello, ${v}</p>-style, where v is untrusted. If v is the string <script>alert(1)</script>, a page that inserts it unchanged now contains a script element. If the page first applies HTML entity encoding, it contains the text &lt;script&gt;alert(1)&lt;/script&gt;, which the browser shows as literal characters. MDN describes output encoding in these terms: the characters that could make a string dangerous are escaped so that they are treated as text instead of as part of a language like HTML, with < becoming &lt; as the example.

    For a place between tags OWASP's rule is to HTML-entity-encode five characters: &, <, >, " and '. The lab's encodeHtml does exactly that.

    The trouble starts when the text goes somewhere else. The table lists the lab's contexts and what each source says to do.

    Context Template What to do If you use the wrong thing
    HTML body <p>Hello, ${v}</p> HTML-entity-encode the five characters No encoding: new elements appear
    Quoted attribute <input value="${v}"> Always quote the attribute, then HTML-entity-encode Without the quotes, see the next row
    Unquoted attribute <input value=${v}> Do not. Quote the attribute A space ends the value, so x onmouseover=... adds an attribute, and HTML encoding does not touch a space
    JavaScript string <script>var name = "${v}";</script> Insert only inside a quoted string, with an encoder made for that context Quote-escaping alone, JSON.stringify alone, or HTML encoding all fail (below)
    URL parameter <a href="/search?q=${v}"> Percent-encode the value only, with encodeURIComponent HTML encoding leaves = and &, so the value can add parameters
    Whole URL <a href="${v}"> Allow-list http: and https: (and relative URLs), reject everything else HTML encoding leaves javascript: untouched

    OWASP's rules behind the table: always surround attribute values with quotation marks (spaces do not end a quoted value); insert string data only inside a quoted string with an encoder that also protects the script context, and do not rely on quote escaping alone; percent-encode parameter values only, not the whole URL.

    Figure 4. Which encoder, for which context

    flowchart TD accTitle: Choosing an output encoding by context accDescr: Start from where the untrusted text will be written. Between tags or in a quoted attribute, use HTML entity encoding. In a script string, use a JavaScript string encoder. In a URL parameter, percent-encode the value. As a whole URL, check the scheme against an allow-list. In a script body, a style body, an event handler or an unquoted attribute, do not put it there at all. Q{"Where does the
    text land?"} -->|"between tags"| B["HTML entity encoding"] Q -->|"quoted attribute value"| A["Quote it, then
    HTML entity encoding"] Q -->|"JavaScript string
    in a script"| J["JavaScript string encoder"] Q -->|"one URL query value"| P["Percent-encode the value"] Q -->|"whole href or src"| U["Allow-list the scheme"] Q -->|"script or style body,
    event handler, unquoted
    attribute, comment"| N["Do not put it there"]

    How to read this: the first question is never "is the input dangerous?" It is "what will read this text next?" Each answer has one safe treatment.

    The URL rows show why the allow-list parses instead of matching a string. The WHATWG URL parser that the lab's checkUrl uses strips tabs, newlines and leading spaces and reads the scheme case-insensitively, so JaVaScRiPt:alert(1), a leading-space version and one with a tab inside the word all parse to the javascript: scheme and are dropped. A blacklist for the lower-case string would miss them.

    The DOM side: textContent and the sinks that parse

    In a script that builds the page, the rule becomes a choice of API. textContent sets a node's content to a single text node, so the browser never parses it as markup. OWASP calls it the safe assignment property and MDN says to use it for plain text. MDN advises against innerHTML for text because it handles raw HTML and can be susceptible to XSS.

    • innerHTML does not run script elements, and that is not a defense. MDN says many other ways exist to craft HTML that runs JavaScript, and shows an img whose onerror runs because its src is invalid. The lab's sanitizer tests use that string.
    • innerText is not a safe stand-in. OWASP warns that, depending on the tag, code can be executed, as with a script element.
    • Strings become code in a few more places. Do not pass a string to setAttribute for an event handler, and do not use eval or string-valued setTimeout on untrusted data. Use JSON.parse, never eval, for JSON, and remember that JSON.stringify is not an output encoder: the lab shows it injectable inside an inline script.

    Frameworks apply the same advice: OWASP says to start from the framework's default output encoding. In React the exception is named so it can be reviewed: dangerouslySetInnerHTML takes { __html: ... }, and React's documentation says that unless the markup is from a completely trusted source it is trivial to introduce an XSS vulnerability, so use it only with trusted and sanitized data. OWASP adds that React 19's blocking of javascript: URLs does not replace your own URL validation.

    When users must write HTML

    Sometimes users must format text: bold, a list, a link. Encoding would show the tags as characters. The options are a restricted markup language (Markdown, rendered on a trusted path, with the result still treated as untrusted) or sanitizing. MDN defines sanitization as removing unsafe features from a string of HTML, and OWASP recommends DOMPurify, says not to change sanitized output afterwards, and says to patch sanitizer libraries regularly.

    A safe sanitizer is an allow-list: tags and attributes you permit, everything else removed. The lab's toy model keeps p, b, i, em, strong, code, ul, ol, li, br and a with href and title, drops script and style with their contents, checks every href with the URL allow-list, decodes character references first (so &#106;avascript: is caught), and rebuilds the output from encoded tokens. It is a teaching model and nothing more. Real sanitizers use the browser's own parser, because a home-made tokenizer and the browser can disagree about a malformed string, and attackers target the disagreement.

    Trusted Types

    Trusted Types make the dangerous sinks refuse plain strings. MDN describes the API as ensuring input has passed through a developer-written transformation function before it reaches an API that might execute it. A policy has methods such as createHTML that return TrustedHTML objects, and the CSP directive require-trusted-types-for makes a sink throw a TypeError for a bare string. The API supplies no policy and no sanitizer: your policy calls one such as DOMPurify. OWASP agrees that Trusted Types check at the sink but do not sanitize. A default policy can catch legacy code, which MDN recommends only for the transition.

    At the time of writing MDN labels Trusted Types "Baseline 2026, newly available" (across the latest browsers since February 2026, possibly not older ones), so check the compatibility table for your users' browsers and treat it as a hardening layer that finds forgotten sinks.

    Defense in depth

    Encoding at the point of output is the main defense. Everything else limits the damage when one place is missed.

    Figure 5. Layers around the one that matters

    Output encoding is the main defense; sanitizing, Trusted Types, a content security policy and cookie flags each reduce what a missed spot can doOutput encoding to Sanitizer (if markup is needed); Sanitizer to Trusted Types (policy calls it); Trusted Types to CSP; CSP to HttpOnlyOutput encoding: per contextOutputencodingper contextSanitizer: when HTML is allowedSanitizerwhen HTML isallowedTrusted Types: sinks refuse stringsTrusted Typessinks refusestringsCSP: backupCSPbackupHttpOnly: limits theftHttpOnlylimits theftif markup is neededpolicy calls it

    How to read this: the left box prevents the bug, the right boxes shrink its impact. OWASP says a content security policy should not be your primary defense mechanism, and the lessons on it are planned for this module.

    • A content security policy is a backup. MDN recommends a strict policy using nonces or hashes, which also disallows inline event handlers, javascript: URLs and eval(). A later lesson in this module covers it.
    • HttpOnly cookies forbid JavaScript from reading a cookie through document.cookie, which MDN says mitigates XSS. MDN also says the cookie is still sent with JavaScript-initiated requests such as fetch(), so injected script can still act as the user: it limits theft, not misuse.
    • A web application firewall is not a substitute, says OWASP, for context-aware encoding, safe DOM APIs or sanitization.

    Choosing

    Figure 6. Encode, sanitize or refuse?

    flowchart TD accTitle: Choosing between encoding, sanitizing and refusing accDescr: If the text is plain, use textContent or encode for the context. If users must supply markup, accept a restricted language or run a maintained sanitizer and enforce Trusted Types. If the text would land in a script body, style body, event handler or unquoted attribute, change the design so it does not. Q1{"Does the user supply
    markup on purpose?"} -->|"no"| E["Plain text:
    textContent or encode
    for the context"] Q1 -->|"yes"| Q2{"Can a restricted
    language do?"} Q2 -->|"yes"| M["Render it on a trusted path,
    treat output as untrusted"] Q2 -->|"no"| S["Maintained sanitizer
    + Trusted Types policy"] E --> Q3{"Would it land in script,
    style, a handler or an
    unquoted attribute?"} Q3 -->|"yes"| R["Redesign: pass data
    another way"] Q3 -->|"no"| D["Done: one encoder
    per context"]

    How to read this: most text is plain, and plain text needs only the right encoder. Markup from users is the expensive branch, so offer it only when the product needs it.

    Choice Gain Cost
    Encode for the context at output Stops the bug at its source One missed spot is a bug
    textContent and framework defaults Removes classes of mistakes Cannot render user markup
    Maintained sanitizer for user HTML Allows formatting A dependency to patch
    Trusted Types Finds forgotten sinks Migration work; check support

    Build it: the right encoder for the right place

    Goal. Run seven encoders against hostile strings in six contexts and see, from a small model of how a parser reads markup, which combinations keep structure and text intact, which inject, and which only garble the text. Then watch an allow-list sanitizer model decide what survives.

    Setup. The lab lives in the course's example workspace (Node 26.13.1, pnpm). It is pure string functions: no DOM, no browser, and nothing is ever executed.

    cd examples/frontend
    pnpm install
    cd labs/xss-output-encoding
    pnpm test          # 36 tests
    node src/demo.ts

    Steps.

    1. Read the matrix in section 1 and predict each INJECTED cell before reading on. A quoted attribute is safe under html but not under quote-only.
    2. Find the unquotedAttribute row: no cell is ok, including html. The fix is to quote the attribute, which is the row above.
    3. In section 2, compare jsString + quote-only with jsString + js-string: the payload's own backslash cancels the escape in front of the quote. Then jsString + json-stringify: the HTML parser ends the script at the closing tag before JavaScript is read.
    4. In section 3, every spelling of javascript: is dropped, but //cdn.partner.example/x.js is accepted because it resolves to https:. A scheme allow-list does not say where a link goes, which matters for redirects.
    5. In section 4, every dangerous construct is gone and the output is rebuilt from encoded tokens.

    Expected output, captured from a real run (Node 26.13.1, 2026-12-01, the lab's demo, node src/demo.ts):

    XSS output encoding: the right encoder depends on where the text lands
    
    === 1. One hostile input per context, run through every encoder
    input 1 (body): <script>alert(1)</script>
    input 2 (quotedAttribute): " onmouseover="alert(1)
    input 3 (unquotedAttribute): x onmouseover=alert(1)
    input 4 (jsString): \";alert(1)//
    input 5 (urlParam): a=1&admin=true
    input 6 (urlWhole): javascript:alert(1)
    input 7 (jsString): </script><b>x</b>
    
    context             input  none           html           quote-only     json-stringify js-string      url-param      url-allow-list
    body                1      INJECTED       ok             INJECTED       INJECTED       garbled        garbled        garbled
    quotedAttribute     2      INJECTED       ok             INJECTED       INJECTED       garbled        garbled        garbled
    unquotedAttribute   3      INJECTED       INJECTED       INJECTED       INJECTED       INJECTED       garbled        garbled
    jsString            4      garbled        garbled        INJECTED       ok             ok             garbled        garbled
    urlParam            5      INJECTED       INJECTED       INJECTED       INJECTED       garbled        ok             INJECTED
    urlWhole            6      INJECTED       INJECTED       INJECTED       INJECTED       ok             ok             ok
    jsString            7      INJECTED       garbled        INJECTED       INJECTED       ok             garbled        garbled
    (ok: structure and text intact. INJECTED: the parser sees new structure or a script URL. garbled: nothing injected, but the reader sees the wrong text.)
    (An unquoted attribute is injectable under every encoder here: the fix is to quote it, which is the quotedAttribute row.)
    
    === 2. What the template turned into, for the instructive cases
    body + none (input 1)
      template: <p>Hello, ${v}</p>
      output:   <p>Hello, <script>alert(1)</script></p>
      verdict:  INJECTED (structure changed: p script /script /p)
    body + html (input 1)
      template: <p>Hello, ${v}</p>
      output:   <p>Hello, &lt;script&gt;alert(1)&lt;/script&gt;</p>
      verdict:  ok (structure unchanged, text intact)
    unquotedAttribute + html (input 3)
      template: <input value=${v}>
      output:   <input value=x onmouseover=alert(1)>
      verdict:  INJECTED (structure changed: input[value,onmouseover])
    jsString + quote-only (input 4)
      template: <script>var name = "${v}";</script>
      output:   <script>var name = "\\";alert(1)//";</script>
      verdict:  INJECTED (breaks out of the string literal)
    jsString + html (input 4)
      template: <script>var name = "${v}";</script>
      output:   <script>var name = "\&quot;;alert(1)//";</script>
      verdict:  garbled (string value differs from the input)
    jsString + json-stringify (input 7)
      template: <script>var name = "${v}";</script>
      output:   <script>var name = "</script><b>x</b>";</script>
      verdict:  INJECTED (closes the script early: script /script b /b /script)
    jsString + js-string (input 7)
      template: <script>var name = "${v}";</script>
      output:   <script>var name = "\x3c\x2fscript\x3e\x3cb\x3ex\x3c\x2fb\x3e";</script>
      verdict:  ok (literal ends where expected, value round-trips)
    urlParam + html (input 5)
      template: <a href="/search?q=${v}">results</a>
      output:   <a href="/search?q=a=1&amp;admin=true">results</a>
      verdict:  INJECTED (query changed: path /search, keys q,admin)
    urlParam + url-param (input 5)
      template: <a href="/search?q=${v}">results</a>
      output:   <a href="/search?q=a%3D1%26admin%3Dtrue">results</a>
      verdict:  ok (structure unchanged, q round-trips)
    urlWhole + html (input 6)
      template: <a href="${v}">profile</a>
      output:   <a href="javascript:alert(1)">profile</a>
      verdict:  INJECTED (href runs as a URL: scheme javascript: is not allowed)
    urlWhole + url-allow-list (input 6)
      template: <a href="${v}">profile</a>
      output:   <a href="#">profile</a>
      verdict:  ok (structure unchanged, unsafe URL neutralised)
    
    === 3. URL allow-list: http, https and relative only
    "https://partner.example/a?b=1"  ok   -> https://partner.example/a?b=1
    "/orders/42#top"                 ok   -> /orders/42#top
    "mailto:help@shop.example"       DROP -> scheme mailto: is not allowed
    "javascript:alert(1)"            DROP -> scheme javascript: is not allowed
    "JaVaScRiPt:alert(1)"            DROP -> scheme javascript: is not allowed
    "  javascript:alert(1)"          DROP -> scheme javascript: is not allowed
    "java\tscript:alert(1)"          DROP -> scheme javascript: is not allowed
    "data:text/html,x"               DROP -> scheme data: is not allowed
    "//cdn.partner.example/x.js"     ok   -> https://cdn.partner.example/x.js
    "ftp://files.shop.example/a"     DROP -> scheme ftp: is not allowed
    
    === 4. Allow-list sanitizer model: what survives
    in:  <p>Nice <b>post</b>, see <a href="https://partner.example/">this</a>.</p>
    out: <p>Nice <b>post</b>, see <a href="https://partner.example/">this</a>.</p>
    in:  Hello<script>alert(1)</script> there
    out: Hello there
    in:  <img src=x onerror=alert(1)>caption
    out: caption
    in:  <a href="javascript:alert(1)" onclick="alert(1)">click</a>
    out: <a>click</a>
    in:  <a href="&#106;avascript:alert(1)">entity</a>
    out: <a>entity</a>
    in:  <p onmouseover="alert(1)" style="x">styled</p>
    out: <p>styled</p>
    in:  <blink>old</blink> & <i>new
    out: old &amp; <i>new</i>
    in:  <svg onload=alert(1)><p>kept?</p></svg>
    out: <p>kept?</p>

    What the lab does not show. It has no browser, so it cannot show that a given browser runs a given string. Its tokenizer is a model, not the HTML Standard's parser, with none of the error recovery of real parsers, and its sanitizer is a toy. The JavaScript string encoder (escapes for everything outside a small safe set) is this lab's own design. The tests prove the properties the lesson states about the model, not that it matches every engine.

    Break it. In a scratch copy of src/encode.ts, change the default: branch of encodeHtml, the apostrophe case, to return c;. The test "encodes the five characters OWASP lists" fails: a single quote is exactly what lets a payload escape a single-quoted attribute. Throw the copy away; the committed file keeps all five.

    Stretch. Pick one: add a CSS context (a fixed property name and an allow-listed value, as OWASP advises); add rel="noopener noreferrer" to the links the sanitizer keeps; or write a string that the lab's tokenizer reads differently from a browser, and say why that argues for a sanitizer built on the browser's own parser.

    NOTE

    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

    A shop's product page writes outside text in four places: reviews (stored HTML from a rich-text editor), a "You searched for ..." line, a seller profile and an inline bootstrap script, all by string concatenation. A planned feature lets sellers add a website that shows as a link. Six engineers work on the page, none of them full-time on security.

    Starting architecture

    Figure 7. Four writes, no common rule

    Starting architecture: four places write outside text into the page, each with its own ad hoc escapingReviews to Page rendering (as HTML); Search line to Page rendering (replace angle brackets); Seller website to Page rendering (into href); Page rendering to PageSERVER AND PAGE CODEReviews: stored HTMLReviewsstored HTMLSearch line: from the URLSearch linefrom the URLSeller website: stored URLSeller websitestored URLPage rendering: string concatenationPage renderingstringconcatenationPage: shop.examplePageshop.exampleas HTMLreplace angle bracketsinto href

    How to read this: three warning boxes feed one renderer that has no per-context rule. Each fix so far was local: a replace on one character here, a regular expression there.

    Options considered

    Option What it fixes What it costs Risk
    Escape all input once when it is saved Looks simple Mangles stored data Wrong in every context but one
    Encode per context at output, sanitize reviews, validate URLs on render Each place gets the right rule A small rendering module and tests Needs discipline in new code
    Add a content security policy first A quick backup Inline script must be reworked Hides the bugs, does not remove them

    The decision

    Field Decision record
    Context Four write sites with ad hoc escaping, user HTML in reviews, and a new user-supplied URL about to ship.
    Decision One rendering module with one function per context. Reviews go through a maintained sanitizer with an allow-list and are not edited afterwards. Every user-supplied href passes a scheme allow-list at render time. The inline bootstrap becomes a data attribute. Trusted Types start in report-only mode.
    Consequences, good Each context has one tested rule; new fields reuse it; forgotten sinks show up in reports.
    Consequences, bad A dependency to keep patched; a migration of the inline script; reports to triage.
    Revisit when The Trusted Types reports are quiet and enforcement can be switched on.

    Rollout and verification

    1. Write the tests first: feed the lab's textbook payloads into every write site in a test environment and assert on structure, as the lab's judge does.
    2. Ship the renderer one page at a time, starting with the new seller link.
    3. Run Trusted Types in report-only mode for a week and fix each reported sink.
    4. Re-validate stored data (seller URLs, review HTML) against the new rules.

    The 2 a.m. failure

    Soon after the seller website field launches, support reports that opening one seller's profile shows a pop-up dialog. The seller's "website" value begins with javascript:. The save-time check only tested that the value contained a dot, and the render step wrote it into href unchanged.

    First three checks: (1) look at the stored value and how it is rendered; (2) search all stored URL fields for any scheme other than http or https; (3) find every other place that writes a stored URL into href or src. Mitigation: switch the profile link off behind its flag, clear the bad values and deploy the render-time allow-list. Follow-up: validate on save too, add the odd spellings to the tests, and review the URL fields in the Trusted Types reports. Save-time validation and render-time encoding protect different things, and only the render-time rule protects data already stored.

    Architect's notes

    • Encode where you write, not where you read, and store the user's text as written.
    • One function per context, in one module, with a test each.
    • Treat every sink as guilty until traced: search for innerHTML, dangerouslySetInnerHTML, eval and URL attributes, and follow the text back.
    • Prefer a framework's default and make its escape hatches loud in review.
    • Layer, but rank honestly: Trusted Types, a content security policy and HttpOnly reduce impact, they do not excuse unencoded output.
    • Validate again at render: stored data may predate today's rules.

    Common mistakes

    • Escaping once at input: wrong in every context but one, and it corrupts the stored text.
    • Using the HTML encoder everywhere: it leaves javascript:, =, & and spaces alone.
    • Leaving attributes unquoted: a space adds an attribute.
    • Treating JSON.stringify as an encoder for inline scripts, or escaping only double quotes: a closing script tag or a backslash defeats both.
    • Blacklisting javascript:: mixed case, spaces, tabs and character references reach the same scheme.
    • Believing innerHTML is safe because script elements do not run: event-handler attributes still do.
    • Editing sanitized HTML, or trusting a home-made sanitizer.
    • Relying on a content security policy or a firewall instead of fixing the output.

    Key takeaways

    • XSS is untrusted text crossing from data to code at a sink; the script runs with the site's authority, so the same-origin policy does not help.
    • Fix it where text is written, because only there is the context known: body, quoted attribute, JavaScript string, URL parameter and whole URL each need a different treatment.
    • Always quote attributes; never put untrusted text in a script body, style body, event handler or comment.
    • Use textContent and framework defaults for plain text; treat innerHTML and dangerouslySetInnerHTML as hazards.
    • For URLs, parse and allow-list schemes; blacklists miss spellings.
    • If users must write HTML, use a maintained allow-list sanitizer, leave its output alone, and add Trusted Types so sinks refuse bare strings.
    • A content security policy, HttpOnly cookies and firewalls are backups; HttpOnly stops script reading the cookie, not sending requests as the user.

    Practice exercises

    Exercise 1 — Starter (45 min): Add two payloads to the hostile list in src/demo.ts (one for a single-quoted attribute, one with a newline in a JavaScript string), predict the matrix row, then run it and explain each wrong prediction.

    Exercise 2 — Intermediate (2 hours): List every place a page you know writes outside text into the page, label each with its context and the function that should be used, and find one that uses a different one.

    Exercise 3 — Advanced (half day): Add a CSS context to the lab (a style attribute from a chosen colour) using a fixed property name and an allow-list of values. Write tests with hostile values and extend the demo matrix.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments