Skip to the page

Forms, TypeScript and security · senior

Security in React apps: XSS surfaces and Server Functions

React escapes text you render, but XSS still gets in through dangerouslySetInnerHTML, user-controlled URLs, unsafe JSON in server HTML, direct DOM writes and third-party scripts; and with Server Components every Server Function is a public endpoint that needs its own auth checks.

The notes

What you must know

  • Safe by default: {userText} is escaped, so <script> in a comment renders as text.
  • Hole 1: dangerouslySetInnerHTML with user content. Sanitise with DOMPurify (allow-list tags/attributes) or render a parsed structure (markdown to elements, mentions to tokens) instead of HTML strings.
  • Hole 2: URLs. href={userUrl} can be javascript:.... React 19 blocks javascript: URLs in src/href (listed as a breaking change in the upgrade guide), but you should still allow-list protocols (http:, https:, mailto:) and handle data: URLs.
  • Hole 3: serialising data into HTML (initial state, JSON-LD): escape < (for example replace with \u003c) so a </script> inside data cannot close the tag.
  • Hole 4: refs and direct DOM: ref.current.innerHTML = ..., eval, new Function, third-party scripts and tag managers.
  • Defence in depth: strict CSP with nonces; Trusted Types (require-trusted-types-for 'script') which React 19.3 supports by passing TrustedHTML objects through unchanged.
  • Tokens: an XSS can read anything in localStorage; prefer httpOnly, Secure, SameSite cookies for sessions, plus CSRF protection (SameSite, origin checks, tokens). Next.js Server Actions compare Origin with Host, but still need authorisation.
  • Server Functions and RSC: validate inputs, check authn/authz inside every function, return minimal data, and patch quickly (React2Shell CVE-2025-55182 was an unauthenticated RCE in the RSC protocol).

The red pen

Common traps: mistake → fix

  • Mistake: "React prevents XSS completely"

    Fix: only for escaped text children and attributes; not for raw HTML, URLs, or direct DOM.

  • Mistake: "Sanitise on input, render anywhere"

    Fix: sanitise/encode for the output context (HTML, URL, script).

  • Mistake: "JWT in localStorage is fine because we use React"

    Fix: any XSS steals it.

Easy to hard

Questions interviewers ask, easy to hard

  1. React escapes output, so are we safe from XSS?
  2. Our feed renders user mentions, links and markdown. What are the risks and defences?
  3. How do you safely render user-provided HTML?
  4. How do CSP and Trusted Types help, and what changed in React 19.3?
  5. Tokens in localStorage vs httpOnly cookies, and CSRF for Server Actions?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview