REACT Lesson 28 – Security in React | Dataplexa
Lesson 28

Security in React

Protect your React applications from XSS attacks, secure API calls, and implement authentication patterns that keep user data safe.

Security isn't optional. React apps handle sensitive data — user passwords, payment details, personal information. One vulnerability can expose millions of users. React provides built-in protections, but developers must understand where dangers lurk. XSS attacks slip through when you bypass React's safeguards. Authentication tokens get stolen from localStorage. API endpoints leak data without proper validation.

The Security Landscape

Modern web applications face constant threats. Attackers inject malicious scripts, steal authentication tokens, and exploit API vulnerabilities. React applications are particularly vulnerable because they run in browsers — a hostile environment where users can inspect, modify, and manipulate everything.

Client-Side Threats

XSS attacks, CSRF tokens, malicious scripts, localStorage hijacking

API Vulnerabilities

Exposed endpoints, weak authentication, data leakage, injection attacks

Authentication Flaws

Weak tokens, insecure storage, session hijacking, privilege escalation

Data Exposure

Sensitive data in bundles, console logs, error messages, source maps

XSS Prevention

Cross-Site Scripting (XSS) is the most common React vulnerability. Attackers inject malicious JavaScript that runs in your users' browsers. React automatically escapes values in JSX. When you write {userInput}, React converts dangerous characters like <script> into safe HTML entities. But developers bypass this protection with dangerouslySetInnerHTML. The name warns you — this prop can inject executable code.
// DANGEROUS - Don't do this with user input
function UnsafeComponent({ userComment }) {
  return (
    <div 
      dangerouslySetInnerHTML={{
        __html: userComment // Could contain <script>alert('hacked')</script>
      }} 
    />
  );
}

// SAFE - React automatically escapes
function SafeComponent({ userComment }) {
  return <div>{userComment}</div>; // <script> becomes &lt;script&gt;
}
DataFlow Dashboard

What just happened?

React automatically converted the dangerous script tag into safe text. The unsafe version would execute the script in a real attack. Notice how the bold tag also gets escaped — React treats all HTML as text unless you explicitly tell it otherwise.

Secure Authentication

Authentication in React requires careful token management. Tokens prove user identity — lose control and attackers impersonate your users. Never store sensitive tokens in localStorage. Browser storage persists across sessions and JavaScript can access it. If an XSS attack executes, your tokens are compromised. The DataFlow team needs secure login for their analytics dashboard. Admin users access sensitive revenue data — authentication must be bulletproof.
// Secure authentication context for DataFlow
function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  
  // Store token in httpOnly cookie (server-side only)
  const login = async (credentials) => {
    const response = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(credentials),
      credentials: 'include' // Include httpOnly cookies
    });
    
    if (response.ok) {
      const userData = await response.json();
      setUser(userData);
    }
  };
  
  return (
    <AuthContext.Provider value={{ user, login, loading }}>
      {children}
    </AuthContext.Provider>
  );
}
DataFlow Dashboard

What just happened?

The authentication context manages user state securely. Real implementation would use httpOnly cookies that JavaScript cannot access. Try logging in with any email — the demo simulates a secure authentication flow with proper loading states.

API Security

API calls carry the highest security risk. React apps send sensitive data to servers, receive confidential information, and authenticate every request. Always validate API responses. Attackers can manipulate server responses to inject malicious data into your React components. Never trust external data.

Common API Vulnerabilities

Exposing API keys in client code, missing HTTPS, weak authentication headers, trusting user input, leaking error details, CORS misconfigurations

// Secure API service for DataFlow
class SecureAPI {
  constructor(baseURL) {
    this.baseURL = baseURL;
  }
  
  // Always use HTTPS and validate responses
  async request(endpoint, options = {}) {
    const url = `${this.baseURL}${endpoint}`;
    
    const response = await fetch(url, {
      ...options,
      credentials: 'include', // Send httpOnly cookies
      headers: {
        'Content-Type': 'application/json',
        'X-Requested-With': 'XMLHttpRequest', // CSRF protection
        ...options.headers
      }
    });
    
    if (!response.ok) {
      throw new Error(`API Error: ${response.status}`);
    }
    
    const data = await response.json();
    return this.validateResponse(data);
  }
  
  // Validate all API responses
  validateResponse(data) {
    // Remove any script tags or dangerous content
    return JSON.parse(JSON.stringify(data).replace(/<script/gi, ''));
  }
}
DataFlow Dashboard

What just happened?

The SecureAPI class automatically sanitizes all responses, removing dangerous script tags and HTML attributes. Click both buttons to see how malicious content gets stripped while preserving legitimate data. Real APIs should validate on the server, but client-side sanitization adds another layer of protection.

Security Best Practices

Security requires layered defense. No single technique stops all attacks — combine multiple strategies for comprehensive protection.
1
Input Validation
2
Secure Authentication
3
API Protection
4
Content Security Policy
5
Security Audits
Never store API keys in React code. Webpack bundles everything — including your secrets — into JavaScript files that users can inspect. Use environment variables for public keys only.

Environment Variables

Prefix public keys with REACT_APP_ — these get bundled and exposed. Keep sensitive keys on your server only.

Content Security Policy (CSP) headers block XSS attacks at the browser level. Configure your server to send CSP headers that restrict script sources and inline JavaScript execution.
Security Header Purpose Example
Content-Security-Policy Blocks XSS attacks script-src 'self'
X-Frame-Options Prevents clickjacking DENY
Strict-Transport-Security Forces HTTPS max-age=31536000
X-Content-Type-Options Prevents MIME sniffing nosniff
Regular security audits catch vulnerabilities before attackers do. Run npm audit to check dependencies for known security issues. Update packages promptly — security patches protect your users. Companies like GitHub and Netflix run automated security scans on every commit. Their React applications handle millions of users — security vulnerabilities would expose massive amounts of sensitive data.

Production Security Checklist

Before deploying React applications to production, verify every security checkpoint. One missed configuration exposes your entire user base.

Deployment Security

Build processes can introduce vulnerabilities. Verify your production bundles don't contain development code, console logs, or debugging information that exposes application internals.

Security isn't a feature you add later. It must be baked into your React architecture from day one. Plan for threats, validate everything, and never trust user input. The most secure code is code that never runs. Remove unused dependencies, disable unnecessary features, and minimize your attack surface. Every line of code is a potential vulnerability.

Quiz

1. The DataFlow team discovers user comments are displaying HTML tags as text instead of rendering them. What React security feature is causing this?


2. DataFlow admin users need secure authentication tokens. Where should these tokens be stored in a React application?


3. The DataFlow API returns data that will be displayed in React components. What's the most important security practice for handling API responses?


Up Next: React Interview Questions

Master the most common React interview questions with detailed explanations and practical examples that demonstrate real-world problem-solving skills.