Featured
- Get link
- X
- Other Apps
🔐 Day 41 — Security Best Practices for React Apps
🔐 Day 41 — Security Best Practices for React Apps
Security is a critical aspect of every web application. In this lesson, we’ll explore common security risks in React apps and how to mitigate them effectively. From protecting against XSS (Cross-Site Scripting) to securing your API keys and setting up Content Security Policy (CSP), we’ll cover it all.
🚫 1. Avoid Directly Injecting HTML
The dangerouslySetInnerHTML prop can expose your app to XSS attacks if used carelessly.
<div dangerouslySetInnerHTML={{ __html: userInput }} />
✅ Instead, sanitize inputs before rendering using libraries like DOMPurify:
import DOMPurify from 'dompurify';
<div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userInput) }} />
🔒 2. Hide API Keys and Secrets
Never expose API keys in frontend code. Store them in environment variables:
// .env REACT_APP_API_URL=https://api.example.com
Access it in your code safely:
const apiUrl = process.env.REACT_APP_API_URL;
🧱 3. Implement Content Security Policy (CSP)
CSP helps prevent injection attacks. Add a meta tag in public/index.html:
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline';" />
🧩 4. Use HTTPS Always
Ensure your app is served via HTTPS to encrypt data between client and server.
💡 5. Validate Inputs on Backend Too
Even if you sanitize on the frontend, always validate and sanitize data on the server. Defense in depth is key!
Popular Posts
📘 Day 36: Understanding the DOM (Document Object Model)
- Get link
- X
- Other Apps
Day 27: Bootstrap Mini Project – Responsive Portfolio Page
- Get link
- X
- Other Apps
Comments
Post a Comment