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
- Text escaping:
{value}becomes a text node.<,>,&and quotes are never interpreted as HTML. - Attributes via DOM APIs:
title={value}sets the property or attribute safely; the value cannot close the attribute and add new ones. - Element validation: React elements must have
$$typeofset to an internal symbol. Since symbols cannot be represented in JSON, a server returning{ type: "script", props: ... }cannot be rendered as an element. - URL warnings: React warns about
javascript:URLs in development and plans to block them. - Named escape hatch:
dangerouslySetInnerHTML={{ __html }}is deliberately awkward so it is easy to spot in code review. - Trusted Types (React 19.3): values like
TrustedHTMLare 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
srcvalues. - Protect against XSS in code outside React (
innerHTMLin 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')">`;23export function Safe() {4 return (5 <div>6 {/* Rendered as visible text, no script runs */}7 <p>{malicious}</p>89 {/* Attribute value is set safely; quotes cannot break out */}10 <input defaultValue={`" onfocus="alert(1)`} />11 </div>12 );13}1415// Fake elements from JSON cannot render: $$typeof is a Symbol, which JSON cannot contain16const 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}2122// The explicit escape hatch: only with sanitized input23// <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.