Cross-site scripting (XSS) is when an attacker gets their own JavaScript to run in your users' browsers, on your domain. From there it can read what the user sees, act as the user and steal session data. React prevents the most common form by default, which leads many teams to assume they are safe. They usually are not, quite.

The three kinds of XSS

  • Stored XSS. Malicious input is saved, for example in a comment or profile field, and served to every visitor who views it.
  • Reflected XSS. Input from a URL or form is echoed straight back in the response.
  • DOM-based XSS. Client-side code takes data from the URL, storage or a message and writes it into the page unsafely.

What React does for you

When you render a value inside JSX, React escapes it. If a user's name is <script>alert(1)</script>, React renders those characters as text rather than executing them. That covers most everyday rendering.

Where React apps still get it wrong

1. dangerouslySetInnerHTML. The name is a warning. Rendering HTML from a CMS, a rich-text editor or an API this way runs any script or event handler inside it.

2. User-controlled URLs. Escaping does not help with href and src. A link to javascript:stealCookies() runs code when clicked. Recent React versions warn about or block javascript: URLs, but you should validate URLs yourself.

3. Direct DOM access. Using a ref to set innerHTML, or calling document.write, bypasses React's escaping entirely.

4. Server-rendered state. Embedding initial data in a <script> tag with plain JSON.stringify lets a value containing </script> break out of the tag. Use a serialiser that escapes <.

5. Third-party code. Markdown renderers configured to allow raw HTML, embed widgets and analytics scripts all run with your page's privileges.

Layer 1: sanitise any HTML you render

If you must render HTML, clean it first with a well-maintained sanitiser such as DOMPurify:

import DOMPurify from 'dompurify';

function RichText({ html }: { html: string }) {
  const clean = DOMPurify.sanitize(html);
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

Better still, avoid raw HTML. Store content as Markdown or structured blocks and render them as React components. For example, react-markdown does not render raw HTML unless you explicitly add a plugin for it.

Layer 2: validate URLs

Allow only the protocols you expect:

function safeUrl(input: string) {
  try {
    const url = new URL(input, window.location.origin);
    return ['http:', 'https:', 'mailto:'].includes(url.protocol) ? url.href : '#';
  } catch {
    return '#';
  }
}

Apply this to any link or image source that comes from users or external data.

Layer 3: Content Security Policy

A Content Security Policy (CSP) header tells the browser which scripts may run. A strict policy using nonces, for example script-src 'nonce-RANDOM' 'strict-dynamic', blocks injected inline scripts even if one slips through. Start in report-only mode to find what would break, then enforce it.

Chromium-based browsers also support Trusted Types, which can be enforced through CSP so that dangerous sinks like innerHTML only accept values that have passed through your sanitiser.

Layer 4: limit the damage

  • Keep session tokens in HttpOnly cookies, which JavaScript cannot read, rather than in localStorage. Add the Secure and SameSite attributes.
  • Use short-lived tokens and re-authenticate for sensitive actions like changing a password or payment details.
  • Keep dependencies updated and run npm audit or a similar scanner in CI.

Layer 5: validate on the server

Client-side validation improves the experience but protects nothing; an attacker can call your API directly. Validate type, length and format on the server, and store data as plain text unless you have a specific reason to store HTML.

Checklist

  • Every use of dangerouslySetInnerHTML is sanitised, or removed.
  • User-supplied URLs are checked against allowed protocols.
  • No refs write to innerHTML.
  • Server-rendered state is serialised safely.
  • A Content Security Policy is in place, at least in report-only mode.
  • Session tokens live in HttpOnly cookies.
  • Inputs are validated on the server.
  • Dependencies are scanned automatically.

React gives you a safe default. These layers make sure the exceptions do not become your weakest point.