React Course
`, an unsafe website might literally print that to the screen, causing","author":{"@type":"Organization","name":"ToolMate"},"publisher":{"@type":"Organization","name":"ToolMate","logo":{"@type":"ImageObject","url":"https://interview.toolmate.co.in/favicon.ico"}}}
React
/
Advanced

XSS Prevention

Definition

Cross-Site Scripting (XSS) is a vulnerability where attackers inject malicious JavaScript into web pages viewed by other users. React automatically protects against most XSS attacks by escaping string variables in JSX.

Explain Like I'm New

If someone fills out a comment form and types `<script>stealPasswords()</script>`, an unsafe website might literally print that to the screen, causing the browser to execute it. React is smart. If you try to render that comment inside a `<div>{comment}</div>`, React converts the `<` and `>` into safe text characters (`&lt;` and `&gt;`). It displays the code as harmless text, rather than executing it.

Real World Example

A user updates their profile name to `<img src='x' onerror='alert("Hacked")' />`. In React, this safely renders as text on the screen. In raw jQuery or vanilla `innerHTML`, this would pop up an alert box.

Common Use Cases

  • •Rendering user-generated content (comments, usernames)
  • •Protecting the application from malicious input

Interactive Example

Loading Code Playground...

Interview Questions

basic

  • How does React prevent XSS attacks automatically?
  • What does 'escaping' mean?

intermediate

  • In what scenario is React NOT safe from XSS?
  • How do attackers steal data using XSS?

advanced

  • How does Server-Side Rendering (SSR) complicate XSS prevention?
  • Can an attacker inject XSS via a JSON API response?

Flash Cards

Question

In what scenario is React NOT safe?

Click to reveal answer
Answer

1. If you use `dangerouslySetInnerHTML`. 2. If you pass user input into an `href` attribute without checking for `javascript:` protocols (e.g., `<a href={userInput}>Link</a>`). 3. If you pass user input into a `<style>` tag or `style` prop unpredictably.

Question

How do attackers steal data?

Click to reveal answer
Answer

They use injected JavaScript to read `document.cookie` (stealing your session token) or `localStorage`, and then send that data to their own server using `fetch()`. They can then log in as you.