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
HttpOnlycookies 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.
- 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.
- 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.
- 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
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
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
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 <script>alert(1)</script>, 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 < 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
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.
innerHTMLdoes not run script elements, and that is not a defense. MDN says many other ways exist to craft HTML that runs JavaScript, and shows animgwhoseonerrorruns because itssrcis invalid. The lab's sanitizer tests use that string.innerTextis not a safe stand-in. OWASP warns that, depending on the tag, code can be executed, as with ascriptelement.- Strings become code in a few more places. Do not pass a string to
setAttributefor an event handler, and do not useevalor string-valuedsetTimeouton untrusted data. UseJSON.parse, nevereval, for JSON, and remember thatJSON.stringifyis 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 javascript: 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
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 andeval(). A later lesson in this module covers it. HttpOnlycookies forbid JavaScript from reading a cookie throughdocument.cookie, which MDN says mitigates XSS. MDN also says the cookie is still sent with JavaScript-initiated requests such asfetch(), 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?
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.
- Read the matrix in section 1 and predict each
INJECTEDcell before reading on. A quoted attribute is safe underhtmlbut not underquote-only. - Find the
unquotedAttributerow: no cell isok, includinghtml. The fix is to quote the attribute, which is the row above. - In section 2, compare
jsString + quote-onlywithjsString + js-string: the payload's own backslash cancels the escape in front of the quote. ThenjsString + json-stringify: the HTML parser ends the script at the closing tag before JavaScript is read. - In section 3, every spelling of
javascript:is dropped, but//cdn.partner.example/x.jsis accepted because it resolves tohttps:. A scheme allow-list does not say where a link goes, which matters for redirects. - 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, <script>alert(1)</script></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 = "\";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&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="javascript: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 & <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.
In practice: reviews, a search line and seller links on a product page
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
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
- 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
judgedoes. - Ship the renderer one page at a time, starting with the new seller link.
- Run Trusted Types in report-only mode for a week and fix each reported sink.
- 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,evaland 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
HttpOnlyreduce 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.stringifyas 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
innerHTMLis 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
textContentand framework defaults for plain text; treatinnerHTMLanddangerouslySetInnerHTMLas 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,
HttpOnlycookies and firewalls are backups;HttpOnlystops 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.
Related reading
In this course:
- The Same-Origin Policy and CORS, what an origin is and why a script that runs in your origin is out of its reach.
- CORS in Practice: Preflights, Credentials and Debugging, how credentialed requests work, which is what an injected script can send.
Official documentation
- OWASP: Cross Site Scripting Prevention Cheat Sheet, the rules by context.
- OWASP: DOM based XSS Prevention Cheat Sheet, the sinks and the safe APIs.
- MDN: Cross-site scripting (XSS), the attack types and the defenses.
- MDN: Element.innerHTML, Security considerations and Node.textContent.
- MDN: Trusted Types API, sinks, policies and enforcement.
- React: dangerouslySetInnerHTML, the documented escape hatch.