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
- 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><script>alert('Hacked!')</script></div>
π React converts <script> into safe HTML entities (<, >), 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
dangerouslySetInnerHTMLwith 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!