XSS and injection in the browser · mid
XSS in React and Next.js: what React protects and where it does not
React escapes text you render in JSX, so most XSS needs an escape hatch: dangerouslySetInnerHTML, user-controlled URLs, server-rendered JSON in a script tag, refs that set innerHTML, or third-party code.
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
- JSX text and attribute values are escaped: {userName} can never become HTML.
- Holes: dangerouslySetInnerHTML with unsanitised HTML; href/src from users (React 19 blocks javascript: URLs, but data: URLs and open redirects still need your own allow-list); ref.current.innerHTML; markdown renderers that allow raw HTML; eval of user strings.
- SSR state injection: writing JSON.stringify(state) into a <script> tag breaks out if the data contains </script>. Escape < as \u003c (or use the framework's serializer).
- Rich text: sanitise with DOMPurify (on the server or before rendering), keep it updated, and do not modify its output afterwards. Better: parse mentions/links into tokens and render React elements.
- Server Components and Server Actions add server-side risks: don't pass secrets into props of client components, and validate and authorise every Server Action (they are public HTTP endpoints).
- React 19.3 supports Trusted Types, so a strict Trusted Types CSP can be enforced in React apps.
The red pen
Common traps: mistake → fix
Mistake: "React prevents XSS completely"
Fix: it escapes text, but escape hatches, URLs, SSR JSON and third-party scripts are still your job.
Mistake: "Sanitise on input and store it"
Fix: sanitiser rules change and output contexts differ; sanitise close to rendering (and keep the raw data).
Mistake: "A Server Action is private because it's not an API route"
Fix: it is reachable by POST from anyone; check auth and input inside it.
Easy to hard
Questions interviewers ask, easy to hard
- React escapes output. So are we safe from XSS?
- Our feed renders mentions, links and markdown. Walk me through the risks.
- How do you safely put initial state into server-rendered HTML?
- How would you add a strict CSP to a Next.js app?
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.