📘 ReactJS

XSS Prevention - Cross-Site Scripting

Cross-Site Scripting occurs when attacker-controlled content is interpreted as executable HTML or JavaScript in a user's browser. React escapes ordinary text rendering by default, but applications can reintroduce risk through unsafe HTML rendering, unsafe DOM APIs, third-party scripts, and insecure content handling.

S

Site Administrator

📅 Sep 28, 2026 🕒 2 min read 👁 26 views
☆ Save 𝕏 in f ✆
XSS Prevention - Cross-Site Scripting

Cross-Site Scripting occurs when attacker-controlled content is interpreted as executable HTML or JavaScript in a user's browser. React escapes ordinary text rendering by default, but applications can reintroduce risk through unsafe HTML rendering, unsafe DOM APIs, third-party scripts, and insecure content handling.

Safe React rendering

const comment = "<img src=x onerror=alert(1)>";

return <p>{comment}</p>;

React treats the value as text rather than intentionally interpreting it as HTML.

Dangerous HTML

return (
  <div
    dangerouslySetInnerHTML={{
      __html: htmlFromUser
    }}
  />
);

This bypasses React's normal escaping behavior and therefore requires strong sanitization and a trusted content pipeline.

DOM XSS

Directly assigning untrusted strings to dangerous DOM sinks can create vulnerabilities. Avoid unsafe innerHTML usage and similar patterns with untrusted content.

Sanitization

If the business requirement genuinely requires rich HTML, sanitize it using a well-maintained sanitizer and enforce a strict content policy. Do not build a home-made HTML sanitizer.

Content Security Policy

A Content Security Policy can reduce the impact of some XSS attacks by restricting which scripts and resources the browser is allowed to execute or load.

Content-Security-Policy:
default-src 'self';
script-src 'self';

Safe output

User comment:
<img src=x onerror=alert(1)>

Rendered screen:
<img src=x onerror=alert(1)>

No JavaScript executes.

Other XSS sources

  • Untrusted HTML from a CMS.
  • Third-party widgets.
  • URL parameters inserted into HTML.
  • Markdown-to-HTML conversion.
  • Unsafe template construction.
  • DOM APIs used with untrusted values.

Common mistakes

  • Using dangerouslySetInnerHTML for convenience.
  • Assuming TypeScript prevents XSS.
  • Trusting data merely because it came from an API.
  • Building custom sanitization logic.
  • Ignoring third-party scripts.

Interview questions

  • Does React prevent XSS automatically?
  • When is dangerouslySetInnerHTML dangerous?
  • What is CSP?
  • How do you safely render rich HTML?

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.

Never miss a new post 📬

Get an email whenever a new article, project, cheatsheet or video drops.

✅

ℹ️