React and XSS

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

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

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

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)

βœ… Avoid dangerouslySetInnerHTML

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

βœ… Use a Content Security Policy (CSP)

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!