JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsreact
PrevNext

Learn the concept

Security

react
senior
security

What security vulnerabilities should you address in React applications and how do you prevent them?

security
xss
csrf
authentication
sanitization
cookies
dompurify
server-components
server-actions
rce
Quick Answer

Key vulnerabilities include XSS (mitigated by React's auto-escaping, but watch dangerouslySetInnerHTML and URL injection), CSRF (use tokens in API requests, SameSite cookies), and insecure storage (avoid localStorage for sensitive data, prefer httpOnly cookies).

Detailed Explanation

XSS (Cross-Site Scripting):

  1. React's Built-in Protection:

    • JSX auto-escapes values in {} by default
    • <div>{userInput}</div> is safe
  2. XSS Vectors to Watch:

    • dangerouslySetInnerHTML - bypasses escaping, sanitize with DOMPurify
    • javascript: URLs in href/src - NOT escaped, validate URLs
    • Inline event handlers from user data

CSRF (Cross-Site Request Forgery):

  • React doesn't prevent CSRF - it's a UI library
  • Include CSRF tokens in state-changing requests
  • Use SameSite=Strict or SameSite=Lax cookies
  • Never use GET for mutations

Authentication & Storage:

  • localStorage is vulnerable to XSS (any script can read it)
  • httpOnly cookies are safer but have CSRF risk
  • Best: httpOnly cookies + CSRF tokens
  • Never store secrets in frontend code

Additional Security Measures:

  • Content Security Policy (CSP) headers
  • HTTPS everywhere, Secure cookie flag
  • Regular npm audit for vulnerable dependencies
  • Input validation on server (frontend is UX only)

React Server Components Security (Critical):

  1. CVE-2025-55182 (React2Shell, CVSS 10.0):

    • Critical RCE in RSC Flight protocol (December 2025)
    • Insecure deserialization allows unauthenticated remote code execution
    • Affected React 19.0-19.2.0, patched in 19.0.1, 19.1.2, 19.2.1
    • Actively exploited in the wild — patch immediately
  2. Follow-up CVEs (December 2025):

    • CVE-2025-55184 / CVE-2025-67779: Denial of service via infinite loop
    • CVE-2025-55183: Source code exposure via Server Function .toString()
    • Patched in React 19.0.3, 19.1.4, 19.2.3
  3. Server Actions Security:

    • Functions marked with "use server" create public HTTP endpoints
    • Always validate inputs, check authentication, authorize access
    • Never trust data from the client — treat Server Actions like API routes
    • Don't pass sensitive data through client-server boundaries

Code Examples

XSS prevention patternsJSX
// SAFE: React auto-escapes by default
function Comment({ text }) {
  return <p>{text}</p>; // <script> becomes &lt;script&gt;
}

// DANGEROUS: dangerouslySetInnerHTML bypasses escaping
function UnsafeHTML({ html }) {
  return <div dangerouslySetInnerHTML={{ __html: html }} />;
}

// SAFE: Sanitize with DOMPurify before using
import DOMPurify from 'dompurify';

function SafeHTML({ html }) {
  const sanitized = DOMPurify.sanitize(html, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],
    ALLOWED_ATTR: ['href', 'target']
  });
  return <div dangerouslySetInnerHTML={{ __html: sanitized }} />;
}

// DANGEROUS: javascript: URL injection
function UnsafeLink({ href, children }) {
  // User could pass: javascript:alert('XSS')
  return <a href={href}>{children}</a>;
}

// SAFE: Validate URL protocol
function SafeLink({ href, children }) {
  const isValidUrl = (url) => {
    try {
      const parsed = new URL(url, window.location.origin);
      return ['http:', 'https:', 'mailto:'].includes(parsed.protocol);
    } catch {
      return false;
    }
  };

  if (!isValidUrl(href)) {
    return <span>{children}</span>; // Render as text
  }
  return <a href={href}>{children}</a>;
}

Real-World Applications

Use Cases

XSS Prevention

Sanitizing user-generated content and avoiding dangerouslySetInnerHTML in React applications

Server Components Security

Validating all Server Action inputs and protecting against RSC Flight protocol vulnerabilities

Supply Chain Security

Auditing React dependencies for known vulnerabilities and maintaining patched versions

Mini Projects

Security Audit Checklist

intermediate

Build an interactive checklist app covering React security best practices with code examples

Vulnerable App Lab

advanced

Create a deliberately vulnerable React app with XSS, CSRF, and injection vectors for security training, then fix each vulnerability

Industry Examples

Vercel

Deployed WAF rules to protect against CVE-2025-55182 (React2Shell) across all hosted projects

Snyk

Provides React-specific security scanning and vulnerability detection

Resources

React Security Best Practices 2025

article

OWASP React Security Cheat Sheet

docs

DOMPurify - Sanitization Library

docs

React Security Advisory - CVE-2025-55182

docs

Related Questions

What is CORS, when do CORS errors occur, and how can they be resolved?

senior
cors

How do Error Boundaries work in React and what are their limitations?

senior
error-handling
Previous
What is Redux and Redux Thunk, and how do they manage application state and async operations?
Next
How would you design and implement a reusable Pagination component in React?
PrevNext