ReactMedium
XSS in React?
Cross-site scripting (XSS) is injecting malicious scripts into a page so they run in other users' browsers, stealing sessions or acting on their behalf. React protects against most XSS by escaping values rendered in JSX, but you can still be vulnerable through dangerouslySetInnerHTML, javascript: URLs in href, spreading untrusted props, injecting into <script> tags during SSR, or unsafe third-party code.
Where React is safe by default
<p>{userInput}</p> renders <script>alert(1)</script> as visible text, because React escapes strings before inserting them into the DOM.
Where XSS still happens
dangerouslySetInnerHTMLwith unsanitized HTML (CMS content, markdown output, comments).- URLs:
<a href={userUrl}>withjavascript:alert(1). React warns in development, but you must validate protocols (http:,https:,mailto:). - Untrusted props spread onto elements:
<div {...userControlledProps}>can injectdangerouslySetInnerHTMLor event handlers. - SSR data injection:
<script>window.__DATA__ = ${JSON.stringify(data)}</script>without escaping<lets</script>break out. - Direct DOM APIs:
element.innerHTML = ...,eval,new Function, or libraries that do this. - Third-party scripts and dependencies that are compromised.
Defenses
- Sanitize HTML with DOMPurify before
dangerouslySetInnerHTML. - Validate URL protocols.
- Never spread unknown objects as props.
- Escape serialized data in SSR (or use framework mechanisms).
- A Content Security Policy (
script-srcwith nonces or hashes) limits damage. - Trusted Types: React 19.3 passes
TrustedHTML/TrustedScriptURLvalues intact to the DOM, so you can enforce Trusted Types policies. httpOnlycookies so scripts cannot read session tokens.
Code example
tsx
1import DOMPurify from "dompurify";23const SAFE_PROTOCOLS = new Set(["http:", "https:", "mailto:"]);45function safeHref(url: string) {6 try {7 const parsed = new URL(url, window.location.origin);8 return SAFE_PROTOCOLS.has(parsed.protocol) ? parsed.href : "#";9 } catch {10 return "#";11 }12}1314export function Comment({ author, website, html }: { author: string; website: string; html: string }) {15 return (16 <article>17 {/* Escaped automatically: "<img onerror=...>" is shown as text */}18 <h3>{author}</h3>1920 {/* Validate URLs: blocks javascript:alert(1) */}21 <a href={safeHref(website)} rel="noopener noreferrer nofollow">Website</a>2223 {/* Sanitize before injecting HTML */}24 <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />25 </article>26 );27}2829// SSR data injection: escape "<" so </script> cannot break out30export const serialize = (data: unknown) => JSON.stringify(data).replace(/</g, "\\u003c");
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.