๐ React Security Kyun Important Hai?
Bahut log sochte hain ki security sirf backend ki responsibility hai, lekin ye galat hai! Frontend security utna hi important hai. Agar tumhara React app secure nahi hai toh:
โ Hackers tumhara data chura sakte hain
โ Malicious code inject kar sakte hain
โ Users ke accounts hijack ho sakte hain
โ Sensitive information leak ho sakti hai
โ App crash ho sakta hai (memory leaks se)
Prevention is better than cure! Ek baar hack ho gaya toh bahut mushkil hai recover karna. Isliye shuru se hi security implement karo! ๐
React security involves implementing multiple layers of protection including XSS (Cross-Site Scripting) prevention, CSRF (Cross-Site Request Forgery) protection, input sanitization, secure state management, memory leak prevention, and proper security headers configuration to protect both the application and its users from various attack vectors.
Major Security Threats
XSS Attack
Attacker malicious JavaScript inject karta hai jo user ke browser mein execute hota hai. Cookies, tokens, sensitive data chura sakte hain.
CriticalCSRF Attack
User ko trick karke unauthorized actions perform karate hain. Bank transfer, password change without user knowing.
High RiskInjection Attacks
Malicious input through forms jo system ko compromise kar sakta hai. SQL injection, command injection.
Medium RiskMemory Leaks
Resources cleanup na hone se memory occupied rehti hai. App slow hota hai, eventually crash kar sakta hai.
Performance๐จ XSS (Cross-Site Scripting) Protection
Imagine karo tum ek comment section bana rahe ho. User comment mein ye likhe:
<script>alert(document.cookie)</script>Agar tum directly ye HTML render kar doge, toh ye script execute ho jayega aur attacker ke paas user ki cookies chali jayengi! ๐ฑ
XSS ke 3 types hain:
1. Stored XSS: Malicious code database mein save hota hai (comments, posts)
2. Reflected XSS: URL parameters mein code (phishing links)
3. DOM-based XSS: Client-side JavaScript manipulation
Cross-Site Scripting (XSS) is a security vulnerability that allows attackers to inject malicious scripts into web pages viewed by other users. These scripts execute in the victim's browser context, potentially stealing cookies, session tokens, or other sensitive information, and can even rewrite HTML content.
๐ฎ Interactive XSS Attack Demo
React's Built-in XSS Protection
Jab tum JSX mein curly braces
{} use karte ho, React automatically escape kar deta hai. Matlab special characters ko safe text mein convert kar deta hai.
Safe HTML Rendering with DOMPurify
XSS Prevention Checklist
| Practice | Description | Status |
|---|---|---|
| Use JSX Expressions | Always use {variable} instead of dangerouslySetInnerHTML | Recommended |
| Sanitize HTML | Use DOMPurify when rendering user HTML | Required |
| Validate Input | Client + Server side validation | Required |
| Content Security Policy | Set CSP headers to restrict script sources | Recommended |
| HttpOnly Cookies | Prevent JavaScript access to cookies | Required |
๐ญ CSRF (Cross-Site Request Forgery) Protection
Imagine karo tum bank ki website pe logged in ho. Attacker ek malicious website banata hai jisme ek hidden form hai:
<form action="https://bank.com/transfer" method="POST">
<input name="to" value="attacker">
<input name="amount" value="10000">
</form>Jab tum us malicious site pe jate ho, form automatically submit ho jata hai. Kyunki tum bank pe logged in ho, tumhare cookies automatically send ho jate hain aur transfer ho jata hai! ๐ฑ
Ye attack isliye kaam karta hai kyunki browser automatically cookies bhejta hai har request ke saath.
Cross-Site Request Forgery (CSRF) is an attack that forces authenticated users to submit a request to a web application against which they are currently authenticated. CSRF attacks exploit the trust that a site has in the user's browser, using the user's authenticated session to perform unauthorized actions.
CSRF Attack Flow
Logged in Bank
Malicious Form
Accepts Request
Unauthorized!
CSRF Protection Methods
Server ek unique token generate karta hai har session ke liye. Ye token form mein include karna padta hai. Attacker ke paas ye token nahi hota, toh request fail ho jati hai! ๐ซ
Ye browser ko batata hai ki cookies sirf same site se requests mein bhejni hain, cross-site requests mein nahi! ๐ช
AJAX requests mein custom header add karo. Simple forms ye header nahi bhej sakte, sirf JavaScript bhej sakta hai! ๐จ
CSRF Protection Comparison
| Method | Security Level | Implementation | Browser Support |
|---|---|---|---|
| CSRF Tokens | High | Medium Complexity | All Browsers |
| SameSite Cookies | High | Easy | Modern Browsers |
| Custom Headers | Medium | Easy | All Browsers |
| Origin Validation | Medium | Easy | All Browsers |
๐งน Input Sanitization
Never trust user input! Ye security ka golden rule hai. User jo bhi input deta hai, usko validate aur sanitize karna zaroori hai. Kyunki:
โ Malicious scripts inject kar sakte hain (XSS)
โ SQL injection attacks kar sakte hain
โ Command injection kar sakte hain
โ Path traversal attacks kar sakte hain
โ Invalid data se app crash ho sakta hai
Validation = Check karo ki data correct format mein hai
Sanitization = Dangerous characters ko remove/escape karo
Input sanitization is the process of cleaning user input by removing or escaping potentially dangerous characters and code. It involves validating input format, length, and type, then transforming it into a safe format before processing or storing. This prevents injection attacks and ensures data integrity.
๐ฎ Interactive Input Sanitization Demo
Validation & Sanitization with Libraries
Common Validation Rules
| Input Type | Validation | Sanitization |
|---|---|---|
| isEmail(), max length 100 | trim(), escape(), toLowerCase() | |
| Password | min 8 chars, complexity rules | No sanitization (hash on server) |
| Username | alphanumeric + underscore, 3-20 chars | trim(), remove special chars |
| Phone | isMobilePhone(), country code | remove spaces, dashes |
| URL | isURL(), allowed protocols | trim(), normalizeURL() |
| Text/Comment | max length, no scripts | escape(), strip HTML tags |
๐ Safe State Updates
React state browser memory mein hota hai, aur Redux DevTools se easily dekha ja sakta hai. Isliye sensitive data state mein store karna dangerous hai! ๐จ
โ State mein NEVER store karo:
โข Passwords (plain text)
โข Credit card numbers
โข Social security numbers
โข API keys / secrets
โข Private keys
โ State mein store kar sakte ho:
โข User ID
โข Username / Email
โข User preferences
โข UI state (modals, tabs, etc.)
โข Non-sensitive user data
Safe state management involves storing only necessary, non-sensitive data in React state or Redux store. Sensitive information should be handled server-side, transmitted securely, and stored in httpOnly cookies or secure storage mechanisms. State should be properly typed, validated, and protected from unauthorized access or manipulation.
Unsafe vs Safe State Management
Secure Token Storage Comparison
| Storage Method | XSS Protection | CSRF Protection | Persistence | Recommendation |
|---|---|---|---|---|
| httpOnly Cookie | Yes | Need SameSite | Until expiry | Best |
| Memory (Variable) | Yes | Yes | Lost on refresh | Good |
| sessionStorage | No | Yes | Until tab close | OK |
| localStorage | No | Yes | Forever | Avoid |
๐พ Avoiding Memory Leaks
Jab component unmount ho jaye (screen se hata diya jaye) lekin uske resources (timers, event listeners, subscriptions) cleanup na ho, toh memory leak hota hai. ๐ณ๏ธ
Kya hota hai memory leak se?
โข Memory occupied rehti hai unnecessarily
โข App slow ho jata hai
โข Battery drain hoti hai
โข Eventually app crash kar sakta hai
โข Mobile devices pe zyada problem
Common causes:
โข setInterval/setTimeout cleanup nahi
โข Event listeners remove nahi kiye
โข WebSocket/SSE connections close nahi kiye
โข Subscriptions unsubscribe nahi kiye
โข Async operations cancel nahi kiye
Memory leaks occur when allocated memory is not properly released after it's no longer needed. In React, this typically happens when components unmount but their side effects (timers, listeners, subscriptions) continue running, preventing garbage collection and causing memory accumulation over time.
๐ฎ Interactive Memory Leak Demo
โ With Memory Leak
Timer continues even after stop!
โ Without Memory Leak
Timer properly cleaned up!
Common Memory Leak Patterns & Fixes
More Memory Leak Examples
Memory Leak Detection
1. Chrome DevTools Memory Profiler:
โข DevTools โ Memory โ Take Heap Snapshot
โข Component mount/unmount karo multiple times
โข Snapshot compare karo
โข Detached DOM nodes dekho
2. React DevTools Profiler:
โข Component render times dekho
โข Unnecessary re-renders identify karo
3. Console Warnings:
โข React Strict Mode warnings
โข "Can't perform a React state update on unmounted component"
4. Performance Monitoring:
โข App slow ho raha hai over time?
โข Memory usage badhta ja raha hai?
โ๏ธ React Helmet - SEO + Security Headers
React Helmet ek library hai jo tumhe document
<head> ko manage karne deti hai React components se! Ye do cheezein provide karta hai:1. SEO: Title, meta tags, Open Graph tags (social media previews)
2. Security: Security headers jo browser ko batate hain ki kaise behave karna hai
Ye especially important hai Single Page Applications (SPA) ke liye kyunki traditional HTML mein head static hota hai, lekin React mein dynamic chahiye! ๐ฏ
React Helmet is a reusable React component that manages changes to the document head. It allows you to set meta tags, title, and security headers dynamically from within React components. This is crucial for SEO in SPAs and for implementing Content Security Policy and other security headers.
Installation & Basic Usage
SEO Meta Tags
Security Headers
โข Content-Security-Policy (CSP): Kahan se scripts load kar sakte hain
โข X-Frame-Options: Iframe mein load ho sakta hai ya nahi (clickjacking prevention)
โข X-XSS-Protection: Browser ka built-in XSS filter enable karo
โข X-Content-Type-Options: MIME type sniffing prevent karo
โข Referrer-Policy: Kitni referrer information bhejni hai
Content Security Policy (CSP) Explained
CSP Directives:
- default-src 'self' - By default sirf apni site se resources load karo
- script-src 'self' cdn.com - Scripts sirf apni site aur cdn.com se
- style-src 'self' 'unsafe-inline' - Styles apni site se + inline styles
- img-src 'self' data: https: - Images apni site, data URLs, aur HTTPS se
- connect-src 'self' api.com - AJAX/WebSocket sirf apni site aur api.com se
- frame-ancestors 'none' - Kisi iframe mein load nahi ho sakta
1. 'unsafe-inline' use karna avoid karo! Ye inline scripts allow karta hai jo XSS vulnerable hai. Lekin React apps mein sometimes zaroori hota hai.
2. Server-side headers better hain! Meta tags se CSP set karna limited hai. Production mein server se headers bhejo (Helmet.js for Express).
3. Testing: CSP violations browser console mein dikhte hain. Pehle report-only mode mein test karo.
Server-side Security Headers (Express + Helmet)
๐ผ Interview Questions
Q1: XSS attack kya hai aur React mein kaise prevent karein? Easy
XSS (Cross-Site Scripting):
XSS ek security vulnerability hai jahan attacker malicious JavaScript code inject karta hai jo victim ke browser mein execute hota hai. Isse attacker cookies steal kar sakta hai, session hijack kar sakta hai, ya user ke behalf pe actions perform kar sakta hai.
Types of XSS:
1. Stored XSS: Malicious code database mein save hota hai (e.g., comments, posts)
2. Reflected XSS: URL parameters mein code (e.g., phishing links)
3. DOM-based XSS: Client-side JavaScript manipulation
React mein Prevention:
1. React's Default Escaping:
React automatically JSX expressions ko escape karta hai:
<div>{userInput}</div> // Safe!
2. Avoid dangerouslySetInnerHTML:
Agar use karna hi hai toh DOMPurify se sanitize karo:
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(html);
<div dangerouslySetInnerHTML={{__html: clean}} />
3. Input Validation & Sanitization:
- Client-side: validator.js use karo
- Server-side: Always validate (client bypass ho sakta hai)
4. Content Security Policy (CSP):
Content-Security-Policy: default-src 'self'; script-src 'self'
5. HttpOnly Cookies:
Cookies ko JavaScript se access nahi hone do
Q2: CSRF attack kaise hota hai aur protection methods kya hain? Medium
CSRF (Cross-Site Request Forgery):
CSRF attack mein attacker authenticated user ko trick karke unauthorized actions perform karata hai. Ye attack isliye successful hota hai kyunki browser automatically cookies bhejta hai har request ke saath.
Attack Example:
User bank site pe logged in hai. Attacker ki malicious site pe ek hidden form hai:
<form action="https://bank.com/transfer" method="POST">
<input name="to" value="attacker" />
<input name="amount" value="10000" />
</form>
<script>document.forms[0].submit();</script>
Form automatically submit ho jata hai aur user ke cookies ke saath request jati hai!
Protection Methods:
1. CSRF Tokens (Most Common):
- Server unique token generate karta hai
- Token form/request mein include karo
- Server verify karta hai
// React
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
fetch('/api/transfer', {
headers: { 'X-CSRF-Token': csrfToken }
});
2. SameSite Cookies:
Set-Cookie: sessionId=abc; SameSite=Strict; Secure; HttpOnly
- Strict: Cross-site requests mein cookies nahi bhejte
- Lax: GET requests allow (navigation)
- None: Sab allow (Secure required)
3. Custom Headers:
AJAX requests mein custom header add karo:
headers: { 'X-Requested-With': 'XMLHttpRequest' }
4. Double Submit Cookie:
- Cookie mein token
- Request body/header mein bhi same token
- Server dono match karta hai
5. Origin/Referer Validation:
Server check karta hai request kahan se aayi hai
Q3: React mein memory leaks kaise hote hain aur kaise prevent karein? Medium
Memory Leaks kya hain:
Jab component unmount ho jaye lekin uske resources (timers, listeners, subscriptions) cleanup na ho, toh memory leak hota hai. Memory occupied rehti hai unnecessarily, app slow hota hai, eventually crash kar sakta hai.
Common Causes & Solutions:
1. Timers (setInterval, setTimeout):
// โ BAD
useEffect(() => {
setInterval(() => console.log('tick'), 1000);
}, []);
// โ
GOOD
useEffect(() => {
const id = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(id);
}, []);
2. Event Listeners:
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
3. WebSocket/SSE Connections:
useEffect(() => {
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('message', handleMessage);
return () => {
socket.removeEventListener('message', handleMessage);
socket.close();
};
}, []);
4. Async Operations:
useEffect(() => {
let cancelled = false;
fetchData().then(data => {
if (!cancelled) setState(data);
});
return () => { cancelled = true; };
}, []);
5. Subscriptions (Redux, RxJS):
useEffect(() => {
const unsubscribe = store.subscribe(handleChange);
return unsubscribe;
}, []);
Detection Methods:
- Chrome DevTools Memory Profiler
- React DevTools Profiler
- Console warnings (React strict mode)
- "Can't perform a React state update on unmounted component" warning
Q4: Input validation aur sanitization mein kya difference hai? Easy
Validation:
Input ko check karna ki wo correct format, type, aur range mein hai ya nahi. Agar invalid hai toh reject kar do.
Examples:
- Email format check: test@example.com
- Password length: minimum 8 characters
- Phone number: 10 digits
- Age: between 18-100
- Username: alphanumeric only
import validator from 'validator';
if (!validator.isEmail(email)) {
return 'Invalid email';
}
if (!validator.isStrongPassword(password)) {
return 'Weak password';
}
Sanitization:
Input ko clean karna by removing or escaping dangerous characters. Data ko safe format mein convert karna.
Examples:
- HTML tags remove karna: <script> โ (removed)
- Special characters escape karna: < โ <
- Whitespace trim karna
- SQL injection characters escape karna
import validator from 'validator';
import DOMPurify from 'dompurify';
// Sanitize email
let email = validator.trim(email);
email = validator.normalizeEmail(email);
email = validator.escape(email);
// Sanitize HTML
const cleanHTML = DOMPurify.sanitize(dirtyHTML);
Key Difference:
- Validation: Check karo โ Accept ya Reject
- Sanitization: Clean karo โ Safe format mein convert
Best Practice:
Dono use karo! Pehle sanitize karo, phir validate karo. Aur hamesha server-side bhi karo, client-side bypass ho sakta hai!
Q5: Content Security Policy (CSP) kya hai aur kaise implement karein? Hard
Content Security Policy (CSP):
CSP ek security layer hai jo browser ko batata hai ki kahan se resources (scripts, styles, images) load karne allowed hain. Ye XSS attacks prevent karta hai by restricting inline scripts aur unauthorized sources.
CSP Directives:
- default-src: Default policy for all resources
- script-src: JavaScript sources
- style-src: CSS sources
- img-src: Image sources
- connect-src: AJAX, WebSocket, EventSource
- font-src: Font sources
- frame-src: iframe sources
- frame-ancestors: Kahan embed ho sakta hai
Implementation Methods:
1. Meta Tag (React Helmet):
import { Helmet } from 'react-helmet';
<Helmet>
<meta
httpEquiv="Content-Security-Policy"
content="
default-src 'self';
script-src 'self' 'unsafe-inline' cdn.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
connect-src 'self' api.com;
"
/>
</Helmet>
2. Server-side Header (Better!):
// Express.js with Helmet
const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "cdn.com"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'", "api.com"]
}
}));
3. Nonce-based CSP (Most Secure):
// Server generates random nonce
const nonce = crypto.randomBytes(16).toString('base64');
// CSP header
Content-Security-Policy: script-src 'nonce-${nonce}'
// HTML
<script nonce="${nonce}">...</script>
Common Issues:
- 'unsafe-inline': Inline scripts/styles allow (less secure)
- 'unsafe-eval': eval() allow (dangerous)
- React inline styles need nonce or hash
Testing:
- Browser console mein CSP violations dikhte hain
- Report-only mode for testing:
Content-Security-Policy-Report-Only: ...Best Practices:
- Start strict, relax as needed
- Avoid 'unsafe-inline' and 'unsafe-eval'
- Use nonces for inline scripts
- Whitelist specific domains, not wildcards
- Monitor CSP reports
Q6: Sensitive data ko React app mein kaise securely store karein? Medium
Rule #1: Never store sensitive data in React state or localStorage!
โ NEVER Store in State/localStorage:
- Passwords (plain text)
- Credit card numbers
- Social security numbers
- API keys / secrets
- Private keys
- Full authentication tokens (if possible)
Why?
- State visible in React DevTools
- localStorage accessible via JavaScript (XSS vulnerable)
- Redux DevTools shows everything
- Browser extensions can access
โ Secure Storage Options:
1. httpOnly Cookies (BEST for tokens):
// Server-side (Express)
res.cookie('authToken', token, {
httpOnly: true, // JavaScript se access nahi
secure: true, // Sirf HTTPS
sameSite: 'strict', // CSRF protection
maxAge: 3600000 // 1 hour
});
// Client automatically bhejta hai cookies
fetch('/api/data', { credentials: 'include' });
2. Memory Storage (for short-term):
// Module-level variable
let authToken = null;
export const setToken = (token) => {
authToken = token;
};
export const getToken = () => authToken;
// Lost on page refresh but secure from XSS
3. sessionStorage (better than localStorage):
// Cleared when tab closes
sessionStorage.setItem('token', token);
// Still XSS vulnerable but better than localStorage
4. Encrypted Storage (if must use localStorage):
import CryptoJS from 'crypto-js';
const SECRET_KEY = 'your-secret-key';
// Encrypt before storing
const encrypted = CryptoJS.AES.encrypt(data, SECRET_KEY);
localStorage.setItem('data', encrypted.toString());
// Decrypt when reading
const decrypted = CryptoJS.AES.decrypt(encrypted, SECRET_KEY);
const data = decrypted.toString(CryptoJS.enc.Utf8);
Best Practices:
- Use httpOnly cookies for authentication tokens
- Never log sensitive data to console
- Disable Redux DevTools in production
- Use environment variables for API keys (server-side)
- Implement token refresh mechanism
- Clear sensitive data on logout
- Use HTTPS always
Q7: Production React app deploy karte waqt kya security measures lene chahiye? Hard
Production Security Checklist:
1. Environment Variables:
// .env.production
REACT_APP_API_URL=https://api.example.com
// Never commit .env files!
// Use in code
const API_URL = process.env.REACT_APP_API_URL;
2. Build Optimization:
// package.json
"build": "GENERATE_SOURCEMAP=false react-scripts build"
// Disable source maps in production
// Minify and uglify code
3. Security Headers (Server):
const helmet = require('helmet');
app.use(helmet({
contentSecurityPolicy: { /* CSP config */ },
hsts: { maxAge: 31536000 },
frameguard: { action: 'deny' },
noSniff: true,
xssFilter: true
}));
4. HTTPS Enforcement:
- SSL/TLS certificate install karo
- HTTP to HTTPS redirect
- HSTS header enable karo
5. Dependency Security:
// Regular audit
npm audit
npm audit fix
// Use Snyk or Dependabot
// Update dependencies regularly
6. API Security:
- Rate limiting implement karo
- CORS properly configure karo
- API keys server-side rakho
- Input validation server-side
- Authentication & Authorization
7. Monitoring & Logging:
- Error tracking (Sentry, Rollbar)
- Security monitoring
- Audit logs
- Performance monitoring
8. Code Security:
- Remove console.logs
- Remove debug code
- Disable React DevTools
- Disable Redux DevTools
- Code obfuscation (optional)
9. Authentication:
- JWT with short expiry
- Refresh token mechanism
- httpOnly cookies
- Logout functionality
- Session timeout
10. Regular Security Audits:
- Penetration testing
- Code reviews
- Security scanning tools
- Stay updated with security patches
๐ Congratulations!
Tumne React Security ka complete journey complete kar liya!
Ab tum secure React applications build kar sakte ho! ๐ก๏ธ