← Back to React, page 3

react-0057 · Medium mid

How does React protect against cross-site scripting (XSS), and where can you still introduce it?

React escapes values placed in JSX, so a string such as an img tag with an onerror handler is shown as text, not run. XSS returns when you bypass that: dangerouslySetInnerHTML with untrusted HTML, javascript: URLs in href, building HTML strings, or injecting unsafe values into places React does not escape, such as script content. Sanitize with a library like DOMPurify, validate URLs, and use a Content Security Policy as a second layer.

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 a javascript: 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.write in effects, and eval or new Function on 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.

jsx
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>&lt;img src="x" onerror="stealCookies()"&gt;&lt;b&gt;Bold&lt;/b&gt;</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.