🛡️ XSS Protection in React
Cross-Site Scripting (XSS) is a common security vulnerability where malicious scripts are injected into web pages viewed by other users. React provides built-in protection, but it's important to understand the risks and best practices.
🔐 1. React Escapes by Default
By default, React escapes all values embedded in JSX. This means user data rendered through JSX cannot run malicious scripts.
const name = "<img src=x onerror=alert('XSS') />";
return <div>Hello {name}</div>; // Safe: React escapes it
☠️ 2. Avoid dangerouslySetInnerHTML
Using dangerouslySetInnerHTML
can bypass React's XSS protections and allow attackers to inject scripts.
// ❌ Dangerous unless sanitized
<div dangerouslySetInnerHTML={{ __html: userInput }} />
If absolutely necessary, sanitize input using libraries like DOMPurify
:
import DOMPurify from 'dompurify';
const safeHtml = DOMPurify.sanitize(userInput);
<div dangerouslySetInnerHTML={{ __html: safeHtml }} />
🌐 3. Be Careful with API Content
- Always assume API data could be unsafe
- Escape or sanitize dynamic content from APIs before rendering as HTML
- Never trust client-side input for rendering raw HTML
🔧 4. Use Content Security Policy (CSP)
Add a CSP header to prevent inline scripts and control script loading:
Content-Security-Policy: default-src 'self'; script-src 'self';
📋 Summary
- React escapes content by default — this protects against XSS
- Never use
dangerouslySetInnerHTML
unless sanitized - Sanitize any untrusted HTML using
DOMPurify
- Enable CSP headers for added protection