XSS Prevention in React and JavaScript
On this page
Learning Objective
Explain how cross-site scripting works and why it is so damaging, distinguish stored, reflected and DOM-based XSS, identify the dangerous sinks in browser APIs and frameworks, render untrusted content safely with escaping and sanitization, and handle URLs, HTML from rich text and markdown correctly.
Concept Explanation
Cross-site scripting, XSS, happens when an attacker gets their own JavaScript to run in your page, in your users' browsers, with your origin's privileges. Once it runs, the script can do anything the legitimate code can: read the page, call your APIs with the user's cookies, change the account email, steal data visible on screen, capture keystrokes or show a fake login form. Because the browser cannot tell your code from injected code, XSS defeats the same-origin policy from the inside. It has been among the most common web vulnerabilities for two decades.
There are three classic forms. Stored XSS saves the payload on the server, for example in a comment or profile name, and serves it to every visitor who views it. Reflected XSS bounces the payload off the server from the request, such as a search term echoed into the results page through a crafted link. DOM-based XSS never touches the server's rendering: client-side code reads attacker-controlled data, from the URL, postMessage, storage or an API, and writes it into a dangerous sink in the DOM. Single page applications are especially exposed to DOM-based XSS because so much rendering happens in the browser.
The root cause is always the same: untrusted data is interpreted as code. A sink is a place where that interpretation happens. HTML parsing sinks include innerHTML, outerHTML, insertAdjacentHTML and document.write. JavaScript execution sinks include eval, new Function, setTimeout and setInterval with string arguments, and inline event handler attributes. URL sinks include href and src attributes and location assignment, where a javascript: URL executes code when followed. Framework escape hatches belong on the list too: React's dangerouslySetInnerHTML, Vue's v-html, Angular's bypassSecurityTrust methods and Svelte's @html.
The first defense is to let the framework escape. React, Vue, Angular and Svelte escape text interpolations by default, so rendering a comment as {comment.body} is safe, exactly like textContent in Day 3. Most XSS in modern apps comes from bypassing that default. When you genuinely need to render HTML, such as content from a rich text editor or markdown converted to HTML, sanitize it with a well-maintained allowlist sanitizer such as DOMPurify, which parses the HTML and removes scripts, event handler attributes, dangerous URLs and other unsafe constructs. Sanitize as close to the sink as possible, with a strict configuration, and keep the library updated. The upcoming native Sanitizer API and setHTML method aim to provide this in the platform.
URLs need their own validation, because escaping does not help when the whole attribute value is a javascript: URL. Allow only http, https and mailto schemes for user-provided links, parse them with the URL constructor and reject anything else. Server-side escaping in templates, output encoding for the right context, and avoiding string concatenation to build HTML complete the picture. Content Security Policy and Trusted Types, Day 92, provide a second layer that limits the damage when a bug slips through.
| Sink or source | Risk | Safe alternative |
|---|---|---|
| innerHTML, insertAdjacentHTML | Parses markup, runs handlers | textContent, createElement, framework text |
| dangerouslySetInnerHTML, v-html | Framework escape hatch | DOMPurify sanitized HTML only |
| eval, new Function, string timers | Executes strings as code | Real functions, JSON.parse for data |
| href and src with user URLs | javascript: URLs execute | Allow http, https, mailto only |
| location from URL parameters | Open redirect or script URL | Allowlist of internal paths |
| postMessage data | Any origin can send | Check event.origin, validate data |
| Markdown to HTML | Embedded HTML and links | Disable raw HTML, sanitize output |
Worked Example: Rendering User Content Safely in React
Comments are rendered as text, a rich bio is sanitized with DOMPurify, user links are restricted to safe schemes and a redirect parameter is checked against internal paths.
import DOMPurify from 'dompurify';
// 1. Plain text: React escapes it, no extra work needed
function Comment({ body }: { body: string }) {
return <p className="comment">{body}</p>; // '<img onerror=...>' shows as text
}
// 2. Rich HTML from an editor: sanitize with a strict allowlist right before the sink
const BIO_CONFIG = {
ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'ul', 'ol', 'li', 'a'],
ALLOWED_ATTR: ['href'],
ALLOWED_URI_REGEXP: /^(?:https?:|mailto:)/i,
};
function Bio({ html }: { html: string }) {
const clean = DOMPurify.sanitize(html, BIO_CONFIG); // removes scripts, handlers, javascript: URLs
return <div className="bio" dangerouslySetInnerHTML={{ __html: clean }} />;
}
// 3. User-supplied links: only safe schemes
export function safeHref(input: string): string | undefined {
try {
const url = new URL(input, window.location.origin);
return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : undefined;
} catch { return undefined; }
}
function Website({ url }: { url: string }) {
const href = safeHref(url);
return href ? <a href={href} rel="noopener noreferrer nofollow" target="_blank">{url}</a> : <span>{url}</span>;
}
// 4. Redirect after login: internal paths only, never an attacker's site or a script URL
export function safeNext(next: string | null): string {
return next && next.startsWith('/') && !next.startsWith('//') && !next.startsWith('/\\') ? next : '/';
}
// 5. postMessage: check who sent it before using the data
window.addEventListener('message', (e) => {
if (e.origin !== 'https://widgets.example.com') return;
const msg = WidgetMessageSchema.safeParse(e.data); // validate the shape (Day 45)
if (msg.success) handleWidgetMessage(msg.data);
});Paste a payload such as an image tag with an onerror handler into each input: the comment displays it as text, the bio keeps the formatting but loses the handler, and a javascript: website link renders as plain text instead of a clickable link.
Real-World Examples
- In 2005 the Samy worm used stored XSS in MySpace profiles to add over one million friends to its author's profile in less than a day, spreading as each infected profile's script ran in the browsers of visitors, and it remains the classic demonstration of how fast stored XSS can propagate.
- In 2010 a stored XSS flaw in Twitter's web client, known as the onMouseOver worm, let tweets containing crafted links execute script when users merely hovered over them, and it spread through retweets to many accounts within hours before Twitter fixed it.
Review Questions & Answers
XSS where the payload never passes through server-side rendering. Client-side JavaScript reads attacker-controlled data, for example from the URL, postMessage or an API response, and writes it into a sink such as innerHTML or a javascript: URL, which executes it in the browser.
Interpolated text is escaped by React and set as text, so markup characters are displayed literally. dangerouslySetInnerHTML passes the string to the HTML parser, so any elements and event handler attributes it contains become real, which can execute script unless the HTML was sanitized.
Escaping prevents breaking out of the attribute, but a value such as javascript:alert(1) is a valid URL that executes when the link is followed. User URLs must be parsed and limited to safe schemes such as http, https and mailto.
It parses untrusted HTML and removes everything not on an allowlist: script elements, event handler attributes, dangerous URL schemes and other unsafe constructs, returning HTML that keeps harmless formatting. It should be used with a strict configuration immediately before the HTML sink.