← Back to React, page 8

react-0145 · Hard senior

How does React protect against XSS by default, where are the escape hatches that break this protection, and how does a Content Security Policy add defence in depth?

React escapes values placed in JSX, so a string is rendered as text and not as HTML. The risky places are dangerouslySetInnerHTML, URLs such as javascript: in href, rendering untrusted HTML from libraries, and direct DOM writes through refs. Sanitize any HTML you must render with a maintained library such as DOMPurify and validate URL schemes. A Content Security Policy (script-src with nonces or hashes, no unsafe-inline) limits the damage if something gets through.

Full answer

Default protection. In JSX, {userInput} is converted to a text node, so <img onerror=...> typed by a user shows as text and does not execute. This covers most cases.

Escape hatches and risks:

  1. dangerouslySetInnerHTML. It inserts raw HTML, so untrusted input leads to XSS. If you must render user or CMS HTML, sanitize it first with DOMPurify (configure the allowed tags), ideally on the server, and keep the call site small and reviewed.
  2. URLs. href={userUrl} with a javascript: URL executes when clicked. Validate that the scheme is http, https or mailto. React warns about javascript: URLs in development and plans to block them in future versions, but you should validate anyway.
  3. Direct DOM writes (ref.current.innerHTML = ...), eval, new Function, and libraries that inject HTML (markdown renderers without sanitization).
  4. Spreading untrusted objects as props (<div {...userProps} />) can set dangerouslySetInnerHTML or event handlers on elements.
  5. Server rendering. Embedding serialized state in a script tag must escape < characters, otherwise </script> in data ends the script. Frameworks do this for you, hand-written SSR often does not.
  6. Third-party scripts and dependencies (supply chain). Pin versions, audit and limit the scripts you load.

Defence in depth with CSP. A Content-Security-Policy header tells the browser which sources of scripts it may run. A strict policy uses nonces or hashes (script-src 'nonce-...' 'strict-dynamic') and avoids 'unsafe-inline' and 'unsafe-eval', so injected inline scripts do not run. Also consider object-src 'none', base-uri 'none', frame-ancestors to prevent clickjacking, and Trusted Types to control DOM sinks. Roll out in report-only mode first. Vite dev tools and some libraries use inline scripts or eval, so test the production build.

Other points: do not store tokens in localStorage if XSS is a concern (prefer httpOnly cookies), use SameSite cookies and CSRF protection, and treat all client-side checks as advisory.

The example demonstrates safe text rendering, a URL validator and sanitizing HTML with an allow-list.

jsx
import { renderToStaticMarkup } from 'react-dom/server';

const attack = '<img src=x onerror="alert(1)">';

function safeHref(url) {
  try {
    const parsed = new URL(url, 'https://example.com');
    return ['http:', 'https:', 'mailto:'].includes(parsed.protocol) ? url : '#';
  } catch {
    return '#';
  }
}

// A deliberately tiny allow-list sanitizer for the demo. Use DOMPurify in real code.
function sanitize(html) {
  return html.replace(/<(?!\/?(b|i|em|strong)\b)[^>]*>/gi, '');
}

console.log('1. text child: ' + renderToStaticMarkup(<p>{attack}</p>));
console.log('2. javascript url is rejected: ' + safeHref('javascript:alert(1)'));
console.log('3. https url is kept: ' + safeHref('https://schoolabe.com'));
console.log('4. sanitized html: ' + renderToStaticMarkup(<p dangerouslySetInnerHTML={{ __html: sanitize('<b>Hello</b><img src=x onerror=alert(1)>') }} />));

This ran as a script with server rendering to a string. The regular text child was escaped. The hand-written sanitizer here is only an allow-list demo and is not safe for production. A real Content Security Policy is an HTTP header enforced by browsers, and this run does not exercise it. Output of the run: 1. text child: <p>&lt;img src=x onerror=&quot;alert(1)&quot;&gt;</p> 2. javascript url is rejected: # 3. https url is kept: https://schoolabe.com 4. sanitized html: <p><b>Hello</b></p>

Key points

  • JSX escapes text by default, so ordinary interpolation is safe.
  • Escape hatches: dangerouslySetInnerHTML, javascript: URLs, direct DOM writes, spread props and unsafe SSR serialization.
  • Sanitize HTML with a maintained library and validate URL schemes.
  • CSP with nonces or hashes and no unsafe-inline limits the damage of an injection.
  • Prefer httpOnly cookies for tokens and keep dependencies audited.

Common mistakes

  • Using dangerouslySetInnerHTML with unsanitized CMS or user content.
  • Allowing javascript: URLs in links from user input.
  • Writing your own sanitizer instead of using a maintained library.
  • Using unsafe-inline in a CSP and believing it still protects scripts.
  • Storing long-lived tokens in localStorage on pages that render untrusted content.

Follow-ups

  • How does a nonce-based CSP work with server rendering?
  • What are Trusted Types, and how do they help?
  • Why is spreading untrusted props risky?

Tips

  • Begin with what React protects and then list the hatches.
  • Say CSP is a second layer and not a replacement for escaping.
  • Name DOMPurify and URL scheme validation.