React Security
Secure your React applications from common vulnerabilities.
Protect React apps from security threats.
Prevent XSS
React escapes by default: ```javascript // Safe <div>{userInput}</div>
// Dangerous - avoid <div dangerouslySetInnerHTML={{__html: userInput}} /> ```
Sanitize HTML
Use DOMPurify: ```bash npm install dompurify ```
```javascript import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(dirty); <div dangerouslySetInnerHTML={{__html: clean}} /> ```
Secure API Keys
Don't expose in client: ```javascript // Bad const API_KEY = 'secret-key-123';
// Good - use environment variables const API_KEY = process.env.REACT_APP_API_KEY; ```
CSRF Protection
Use tokens for state-changing requests: ```javascript fetch('/api/update', { method: 'POST', headers: { 'X-CSRF-Token': csrfToken }, body: JSON.stringify(data) }); ```
Content Security Policy
Add CSP headers: ``` Content-Security-Policy: default-src 'self' ```
Remember
- Sanitize user input - Secure API keys - Use HTTPS - Implement auth properly - Keep dependencies updated
> Next: Learn monitoring and logging!