๐Ÿ›ก๏ธ React Security

XSS, CSRF, Input Sanitization, Memory Leaks aur Security Headers ka complete guide

๐Ÿ”’ React Security Kyun Important Hai?

Security ka matlab sirf backend nahi 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! ๐Ÿ”
Technical Definition:
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.

Critical
๐ŸŽญ

CSRF Attack

User ko trick karke unauthorized actions perform karate hain. Bank transfer, password change without user knowing.

High Risk
๐Ÿ’‰

Injection Attacks

Malicious input through forms jo system ko compromise kar sakta hai. SQL injection, command injection.

Medium Risk
๐Ÿ’พ

Memory 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

XSS kya hai aur kaise hota hai?

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
Technical Definition:
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

๐Ÿ’ก Try entering malicious scripts above and see the difference!
Examples: <script>alert('XSS')</script> or <img src=x onerror="alert(1)">

React's Built-in XSS Protection

Good news! React by default tumhe protect karta hai! ๐ŸŽ‰

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 - React Automatic Escaping:
// React automatically escapes this function UserComment({ comment }) { return ( <div> {comment} // Safe! React escapes automatically </div> ); } // Even if comment contains: const malicious = '<script>alert("XSS")</script>'; // React will render it as text, not execute it!
โŒ DANGEROUS - dangerouslySetInnerHTML:
// This is VULNERABLE to XSS! function UnsafeComponent({ html }) { return ( <div dangerouslySetInnerHTML={{ __html: html }} /> ); } // Attacker can inject: const attack = '<img src=x onerror="alert(document.cookie)">'; // This will EXECUTE! ๐Ÿšจ

Safe HTML Rendering with DOMPurify

Agar tumhe HTML render karna hi hai (rich text editor, markdown), toh DOMPurify library use karo. Ye malicious code ko clean kar deta hai! ๐Ÿงน
โœ… SAFE - Using DOMPurify:
// Install: npm install dompurify import DOMPurify from 'dompurify'; function SafeHTMLComponent({ html }) { // Sanitize the HTML first const cleanHTML = DOMPurify.sanitize(html, { ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'], ALLOWED_ATTR: ['href'] }); return ( <div dangerouslySetInnerHTML={{ __html: cleanHTML }} /> ); } // DOMPurify removes malicious scripts automatically! const input = '<p>Hello</p><script>alert("XSS")</script>'; const clean = DOMPurify.sanitize(input); // Result: '<p>Hello</p>' (script removed!)

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

CSRF kya hai?

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.
Technical Definition:
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

๐Ÿ‘ค
User

Logged in Bank

โ†’
๐Ÿฆน
Attacker Site

Malicious Form

โ†’
๐Ÿฆ
Bank Server

Accepts Request

โ†’
๐Ÿ’ธ
Money Transfer

Unauthorized!

CSRF Protection Methods

1. CSRF Tokens (Most Common):
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! ๐ŸŽซ
// Backend - Generate CSRF token const csrf = require('csurf'); const csrfProtection = csrf({ cookie: true }); app.get('/form', csrfProtection, (req, res) => { res.render('form', { csrfToken: req.csrfToken() }); }); // Frontend - React component function TransferForm() { const [csrfToken, setCsrfToken] = useState(''); useEffect(() => { // Get CSRF token from meta tag or API const token = document .querySelector('meta[name="csrf-token"]') ?.getAttribute('content'); setCsrfToken(token); }, []); const handleSubmit = async (e) => { e.preventDefault(); await fetch('/api/transfer', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': csrfToken // Include token! }, body: JSON.stringify({ amount: 100, to: 'user123' }) }); }; return <form onSubmit={handleSubmit}>...</form>; }
2. SameSite Cookies (Modern Approach):
Ye browser ko batata hai ki cookies sirf same site se requests mein bhejni hain, cross-site requests mein nahi! ๐Ÿช
// Backend - Set SameSite cookie res.cookie('sessionId', 'abc123', { httpOnly: true, // JavaScript se access nahi ho sakti secure: true, // Sirf HTTPS pe sameSite: 'strict' // Cross-site requests mein nahi bhejni }); // SameSite options: // 'strict' - Sabse secure, koi cross-site request nahi // 'lax' - GET requests allow (navigation), POST nahi // 'none' - Sab allow (Secure flag required)
3. Custom Headers:
AJAX requests mein custom header add karo. Simple forms ye header nahi bhej sakte, sirf JavaScript bhej sakta hai! ๐Ÿ“จ
// Frontend - Add custom header const makeRequest = async () => { await fetch('/api/data', { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' }, credentials: 'include' // Include cookies }); }; // Backend - Verify custom header app.post('/api/data', (req, res) => { if (req.get('X-Requested-With') !== 'XMLHttpRequest') { return res.status(403).send('Forbidden'); } // Process request... });

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

Input Sanitization kyun zaroori hai?

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
Technical Definition:
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

๐Ÿ’ก Enter different inputs and see validation in action!

Validation & Sanitization with Libraries

// Install: npm install validator import validator from 'validator'; function LoginForm() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [errors, setErrors] = useState({}); const handleEmailChange = (e) => { let value = e.target.value; // 1. Sanitize - Remove dangerous characters value = validator.escape(value); value = validator.trim(value); // 2. Validate - Check format if (!validator.isEmail(value)) { setErrors(prev => ({ ...prev, email: 'Invalid email format' })); } else { setErrors(prev => ({ ...prev, email: null })); } setEmail(value); }; const handlePasswordChange = (e) => { let value = e.target.value; // Validate password strength if (!validator.isStrongPassword(value, { minLength: 8, minLowercase: 1, minUppercase: 1, minNumbers: 1, minSymbols: 1 })) { setErrors(prev => ({ ...prev, password: 'Password too weak' })); } else { setErrors(prev => ({ ...prev, password: null })); } setPassword(value); }; const handleSubmit = async (e) => { e.preventDefault(); // Final validation before submit if (Object.values(errors).some(err => err)) { alert('Please fix errors first'); return; } // Submit to server (server will validate again!) await fetch('/api/login', { method: 'POST', body: JSON.stringify({ email, password }) }); }; return ( <form onSubmit={handleSubmit}> <input type="email" value={email} onChange={handleEmailChange} maxLength={100} /> {errors.email && <span>{errors.email}</span>} <input type="password" value={password} onChange={handlePasswordChange} maxLength={50} /> {errors.password && <span>{errors.password}</span>} <button type="submit">Login</button> </form> ); }

Common Validation Rules

Input Type Validation Sanitization
Email 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
โš ๏ธ Important: Client-side validation sirf UX ke liye hai! Server-side validation zaroori hai kyunki attacker client-side validation ko bypass kar sakta hai. Always validate on both sides! ๐Ÿ”’

๐Ÿ” Safe State Updates

State mein kya store karna chahiye aur kya nahi?

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
Technical Definition:
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

โŒ UNSAFE - Storing Sensitive Data:
// DON'T DO THIS! const [user, setUser] = useState({ id: 1, name: 'John Doe', email: 'john@example.com', password: 'myPassword123', // โŒ NEVER! creditCard: '1234-5678-9012-3456', // โŒ NEVER! ssn: '123-45-6789' // โŒ NEVER! }); // Storing tokens in localStorage (XSS vulnerable) localStorage.setItem('authToken', token); // โŒ BAD! // Redux DevTools will show everything! const store = createStore(reducer); // All state visible
โœ… SAFE - Proper State Management:
// Store only non-sensitive data const [user, setUser] = useState({ id: 1, name: 'John Doe', email: 'john@example.com', role: 'user', preferences: { theme: 'dark', language: 'en' } }); // Token storage options: // 1. httpOnly Cookie (BEST - server-side only) // Set-Cookie: token=xyz; HttpOnly; Secure; SameSite=Strict // JavaScript cannot access this! // 2. Memory storage (lost on refresh but secure) let authToken = null; export const setToken = (token) => { authToken = token; }; export const getToken = () => { return authToken; }; // 3. SessionStorage (better than localStorage) // Cleared when tab closes sessionStorage.setItem('token', token); // Redux DevTools - Disable in production const store = createStore( reducer, process.env.NODE_ENV === 'development' ? window.__REDUX_DEVTOOLS_EXTENSION__?.() : undefined );

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

Memory Leak kya hai?

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
Technical Definition:
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

0

Timer continues even after stop!

โœ… Without Memory Leak

0

Timer properly cleaned up!

๐Ÿ’ก Start both components and then stop them. Notice the difference!

Common Memory Leak Patterns & Fixes

โŒ MEMORY LEAK - setInterval without cleanup:
// BAD - Memory leak! function BadComponent() { const [count, setCount] = useState(0); useEffect(() => { setInterval(() => { setCount(c => c + 1); }, 1000); // No cleanup! Timer keeps running! ๐Ÿšจ }, []); return <div>{count}</div>; }
โœ… FIXED - Proper cleanup:
// GOOD - Cleanup function! function GoodComponent() { const [count, setCount] = useState(0); useEffect(() => { const intervalId = setInterval(() => { setCount(c => c + 1); }, 1000); // Cleanup function - runs when component unmounts return () => { clearInterval(intervalId); console.log('Cleaned up!'); }; }, []); return <div>{count}</div>; }

More Memory Leak Examples

// 1. Event Listeners function WindowResizeComponent() { const [width, setWidth] = useState(window.innerWidth); useEffect(() => { const handleResize = () => { setWidth(window.innerWidth); }; window.addEventListener('resize', handleResize); // Cleanup - remove listener return () => { window.removeEventListener('resize', handleResize); }; }, []); return <div>Width: {width}</div>; } // 2. WebSocket Connections function ChatComponent() { const [messages, setMessages] = useState([]); useEffect(() => { const socket = new WebSocket('ws://localhost:8080'); socket.addEventListener('message', (event) => { setMessages(prev => [...prev, event.data]); }); // Cleanup - close connection return () => { socket.close(); }; }, []); return <div>{messages.map(m => <p>{m}</p>)}</div>; } // 3. Async Operations function DataFetchComponent() { const [data, setData] = useState(null); useEffect(() => { let cancelled = false; const fetchData = async () => { const response = await fetch('/api/data'); const result = await response.json(); // Only update if not cancelled if (!cancelled) { setData(result); } }; fetchData(); // Cleanup - mark as cancelled return () => { cancelled = true; }; }, []); return <div>{data}</div>; } // 4. Subscriptions (Redux, RxJS, etc.) function ReduxComponent() { const [state, setState] = useState(store.getState()); useEffect(() => { // Subscribe to store const unsubscribe = store.subscribe(() => { setState(store.getState()); }); // Cleanup - unsubscribe return unsubscribe; }, []); return <div>{state.value}</div>; }

Memory Leak Detection

Kaise pata chalega ki memory leak hai?

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 kya hai?

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! ๐ŸŽฏ
Technical Definition:
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

// Install React Helmet npm install react-helmet // Basic usage import { Helmet } from 'react-helmet'; function HomePage() { return ( <> <Helmet> <title>Home - My Secure App</title> <meta name="description" content="Welcome to my secure React app" /> </Helmet> <div> <h1>Welcome!</h1> </div> </> ); }

SEO Meta Tags

function ProductPage({ product }) { return ( <> <Helmet> {/* Basic SEO */} <title>{product.name} - Buy Now</title> <meta name="description" content={product.description} /> <meta name="keywords" content={product.tags.join(', ')} /> {/* Open Graph - Facebook, LinkedIn */} <meta property="og:title" content={product.name} /> <meta property="og:description" content={product.description} /> <meta property="og:image" content={product.image} /> <meta property="og:url" content={window.location.href} /> <meta property="og:type" content="product" /> {/* Twitter Card */} <meta name="twitter:card" content="summary_large_image" /> <meta name="twitter:title" content={product.name} /> <meta name="twitter:description" content={product.description} /> <meta name="twitter:image" content={product.image} /> {/* Canonical URL - Prevent duplicate content */} <link rel="canonical" href={window.location.href} /> </Helmet> <div> <h1>{product.name}</h1> <p>{product.description}</p> </div> </> ); }

Security Headers

Security headers browser ko batate hain ki kaise behave karna hai:

โ€ข 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
function App() { return ( <> <Helmet> {/* Content Security Policy - Most Important! */} <meta httpEquiv="Content-Security-Policy" content=" default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.example.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://api.example.com wss://api.example.com; frame-ancestors 'none'; " /> {/* Prevent Clickjacking */} <meta httpEquiv="X-Frame-Options" content="DENY" /> {/* XSS Protection */} <meta httpEquiv="X-XSS-Protection" content="1; mode=block" /> {/* Prevent MIME Sniffing */} <meta httpEquiv="X-Content-Type-Options" content="nosniff" /> {/* Referrer Policy */} <meta name="referrer" content="strict-origin-when-cross-origin" /> {/* Force HTTPS */} <meta httpEquiv="Strict-Transport-Security" content="max-age=31536000; includeSubDomains" /> </Helmet> <div>Your app content</div> </> ); }

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
โš ๏ธ Important Notes:

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)

// Backend - Express.js with Helmet const express = require('express'); const helmet = require('helmet'); const app = express(); // Use Helmet for security headers app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'unsafe-inline'", "cdn.example.com"], styleSrc: ["'self'", "'unsafe-inline'", "fonts.googleapis.com"], imgSrc: ["'self'", "data:", "https:"], connectSrc: ["'self'", "api.example.com"], fontSrc: ["'self'", "fonts.gstatic.com"], frameAncestors: ["'none'"] } }, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true } })); // Your routes... app.get('/', (req, res) => { res.sendFile(__dirname + '/build/index.html'); }); app.listen(3000);

๐Ÿ’ผ Interview Questions

Q1: XSS attack kya hai aur React mein kaise prevent karein? Easy

Answer:

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

Answer:

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

Answer:

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

Answer:

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: < โ†’ &lt;
- 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

Answer:

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

Answer:

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

Answer:

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! ๐Ÿ›ก๏ธ

๐Ÿ† ๐Ÿ’ช ๐Ÿ”’ โšก ๐Ÿ”ฅ