Does React Offer XSS Safety by Default?

Yes, React provides built-in protection against Cross-Site Scripting (XSS) attacks by default. However, it is not completely immune to XSSβ€”developers must still follow security best practices.


1. How React Protects Against XSS

βœ… Escapes User Input Automatically

  • React automatically escapes values before rendering them into the DOM.
  • This prevents attackers from injecting malicious JavaScript.

Example: React Escaping HTML

const userInput = "<script>alert('Hacked!')</script>"
return <div>{userInput}</div>

Output in the DOM (Safe):

<div>&lt;script&gt;alert('Hacked!')&lt;/script&gt;</div>

πŸš€ React converts <script> into safe HTML entities (&lt;, &gt;), preventing execution.


2. When React is Vulnerable to XSS

Although React protects against most XSS cases, it becomes vulnerable if you bypass its default protections.

πŸ”΄ Using dangerouslySetInnerHTML

  • This method directly injects raw HTML into the DOM, making it prone to XSS.
  • Never use dangerouslySetInnerHTML with untrusted data.

Example of XSS Vulnerability

const userInput = "<img src=x onerror=alert('XSS') />"
return <div dangerouslySetInnerHTML={{ __html: userInput }} />

❌ This executes JavaScript when the image fails to load, causing an XSS attack.

πŸ”΄ Injecting Data into Event Handlers

  • If you directly insert user input into an event handler, React does not escape it.

Example of Unsafe Event Handler

const userInput = "alert('Hacked!')"
return <button onClick={userInput}>Click Me</button>

❌ This executes the alert when the button is clicked, leading to XSS.


3. How to Prevent XSS in React

βœ… Always Escape User Input (React Does This by Default)

  • React automatically sanitizes content inside JSX ({userInput}).

βœ… Avoid dangerouslySetInnerHTML

  • If you must use it, sanitize the input first using a library like DOMPurify.

Example: Safe Use of dangerouslySetInnerHTML

import DOMPurify from "dompurify"
 
const safeHTML = DOMPurify.sanitize(userInput)
return <div dangerouslySetInnerHTML={{ __html: safeHTML }} />

βœ” This ensures that any malicious scripts are removed.

βœ… Use Trusted Sources for Dynamic Content

  • Do not load HTML content from untrusted APIs or user input.

βœ… Use a Content Security Policy (CSP)

  • Implement CSP headers to block inline scripts and reduce XSS risk.
Content-Security-Policy: default-src 'self'; script-src 'self';

Final Verdict

πŸ”Ή React provides strong XSS protection by default through automatic HTML escaping.
πŸ”Ή React is only vulnerable when developers bypass its safeguards (e.g., using dangerouslySetInnerHTML).
πŸ”Ή Following best practices (sanitization, avoiding raw HTML injection) ensures React apps remain secure.

πŸš€ Bottom Line: React is safe from XSS unless you make it unsafe!