Top 5 Security Vulnerabilities in React Apps (and How to Fix Them)

September 15, 2023

React is powerful, but without care, it can be vulnerable. Let's look at common pitfalls.

1. Cross-Site Scripting (XSS)

React automatically escapes JSX content, which prevents many XSS attacks. However, using dangerouslySetInnerHTML can expose you to risk.


// Vulnerable code
function UserProfile({ bio }) {
  return 
; } // Safer approach: Sanitize the HTML before rendering import DOMPurify from 'dompurify'; function SafeUserProfile({ bio }) { const cleanBio = DOMPurify.sanitize(bio); return
; }

2. Insecure Component Rendering

Never render components based on user-provided JSON structures without validation. This could lead to arbitrary component rendering.


// Unsafe: User can specify any component name to render
const components = { SpecialAdminComponent, UserComponent };
const ComponentToRender = components[userInput.componentName];
return ;

// Safer: Use an allow-list
const allowedComponents = { 'UserComponent': UserComponent };
const ComponentToRender = allowedComponents[userInput.componentName];
if (!ComponentToRender) throw new Error('Component not allowed');
return ;
      

Always validate and sanitize user input, even when working within a framework like React.