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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Safe by default:
{userText}is escaped, so<script>in a comment renders as text. - Hole 1:
dangerouslySetInnerHTMLwith 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 bejavascript:.... React 19 blocksjavascript:URLs insrc/href(listed as a breaking change in the upgrade guide), but you should still allow-list protocols (http:,https:,mailto:) and handledata: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
- React escapes output, so are we safe from XSS?
- Our feed renders user mentions, links and markdown. What are the risks and defences?
- How do you safely render user-provided HTML?
- How do CSP and Trusted Types help, and what changed in React 19.3?
- 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 voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.