ReactMedium

How React prevents XSS?

React prevents most XSS by treating everything you render as data, not markup: strings and numbers in JSX are escaped before reaching the DOM (React sets text content, never innerHTML), attribute values are set through DOM properties, and React elements carry a special $$typeof symbol so JSON data cannot be smuggled in as fake elements. Only explicit escape hatches like dangerouslySetInnerHTML bypass this.

The mechanisms

  1. Text escaping: {value} becomes a text node. <, >, & and quotes are never interpreted as HTML.
  2. Attributes via DOM APIs: title={value} sets the property or attribute safely; the value cannot close the attribute and add new ones.
  3. Element validation: React elements must have $$typeof set to an internal symbol. Since symbols cannot be represented in JSON, a server returning { type: "script", props: ... } cannot be rendered as an element.
  4. URL warnings: React warns about javascript: URLs in development and plans to block them.
  5. Named escape hatch: dangerouslySetInnerHTML={{ __html }} is deliberately awkward so it is easy to spot in code review.
  6. Trusted Types (React 19.3): values like TrustedHTML are passed to the browser intact, so you can enforce a Trusted Types policy that requires sanitization.

What React does not do

  • Sanitize HTML you inject.
  • Validate URLs or src values.
  • Protect against XSS in code outside React (innerHTML in effects, third-party widgets, eval).
  • Protect server-rendered inline scripts you build by string concatenation.

Complementary defenses

DOMPurify for HTML, a strict Content Security Policy, httpOnly cookies, dependency auditing, and Trusted Types.

Code example

tsx
1const malicious = `<img src=x onerror="alert('xss')">`;
2
3export function Safe() {
4 return (
5 <div>
6 {/* Rendered as visible text, no script runs */}
7 <p>{malicious}</p>
8
9 {/* Attribute value is set safely; quotes cannot break out */}
10 <input defaultValue={`" onfocus="alert(1)`} />
11 </div>
12 );
13}
14
15// Fake elements from JSON cannot render: $$typeof is a Symbol, which JSON cannot contain
16const fromApi = JSON.parse('{"type":"script","props":{"children":"alert(1)"}}');
17export function Fake() {
18 // Rendering `fromApi` directly throws "Objects are not valid as a React child"
19 return <pre>{JSON.stringify(fromApi)}</pre>;
20}
21
22// The explicit escape hatch: only with sanitized input
23// <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app