Full answer
XSS means an attacker gets their JavaScript to run in your user's session, usually through content you display: a comment, a profile bio, a query parameter. The script can read tokens that are available to JavaScript and act as the user.
JSX protects you by default. {userInput} becomes a text node, so markup characters are escaped. This is why most React apps are safe from the common case.
The ways around it:
dangerouslySetInnerHTML={{ __html: html }}inserts raw HTML. The name is a warning. If html contains untrusted content, it can contain scripts or event handler attributes. Sanitize first with DOMPurify, ideally on the server too, and prefer rendering Markdown through a parser configured to disallow raw HTML.- URLs.
<a href={userUrl}>accepts ajavascript:URL, which runs when clicked. Allow only http, https and mailto by parsing the URL and checking the protocol. React 19 still warns about javascript: URLs, but warnings are not protection. - Direct DOM writes with innerHTML or
document.writein effects, andevalornew Functionon user data. - Server-rendered pages that embed JSON in a script tag without escaping the closing tag sequence.
- Third-party scripts and dependencies, which run with full rights. Use subresource integrity and audit packages.
Defence in depth: a Content Security Policy that blocks inline scripts limits the damage of a missed case. Store session tokens in HttpOnly cookies, so scripts cannot read them. Keep user-controlled data away from style and URL contexts.
The example shows plain text, a sanitized fragment and a URL check.
import DOMPurify from 'dompurify';
const untrusted = '<img src="x" onerror="stealCookies()"><b>Bold</b>';
function safeHref(url) {
try {
const parsed = new URL(url, 'https://example.com');
return ['http:', 'https:', 'mailto:'].includes(parsed.protocol) ? parsed.href : '#';
} catch {
return '#';
}
}
function Comment({ html }) {
return <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(html) }} />;
}
export default function App() {
return (
<div>
<p>{untrusted}</p>
<Comment html={untrusted} />
<a href={safeHref('javascript:alert(1)')}>Blocked link</a>
<a href={safeHref('https://schoolabe.com')}>Allowed link</a>
</div>
);
}The first line is escaped text. The second goes through DOMPurify, which removes the onerror attribute. The unsafe link becomes a hash. This used the dompurify package with jsdom. Rendered result: <div><p><img src="x" onerror="stealCookies()"><b>Bold</b></p><div><img src="x"><b>Bold</b></div><a href="#">Blocked link</a><a href="https://schoolabe.com/">Allowed link</a></div>
Key points
- JSX escapes text by default, which blocks most XSS.
- dangerouslySetInnerHTML needs sanitized HTML. DOMPurify is the usual tool.
- Validate URL protocols to block javascript: links.
- Avoid innerHTML, eval and unescaped JSON in script tags.
- Add a Content Security Policy and HttpOnly cookies as extra layers.
Common mistakes
- Using dangerouslySetInnerHTML with unsanitized API content.
- Checking URLs with a string prefix test instead of parsing them.
- Believing a framework makes every output safe.
- Storing tokens in localStorage where any injected script can read them.
- Sanitizing only on the client when the HTML is stored and reused elsewhere.
Follow-ups
- What does a Content Security Policy add if sanitization already runs?
- Why are HttpOnly cookies safer for session tokens?
- How would you render user-written Markdown safely?
Tips
- Start from "JSX escapes by default", then list the exceptions. It shows you know the baseline.
- Name DOMPurify and URL protocol checks as concrete defences.
- Mention CSP and cookies as defence in depth.