React Security Best Practices

Security is a critical aspect of web development. Fortunately, React comes with built-in protections, but developers must still follow best practices to avoid vulnerabilities like XSS (Cross-Site Scripting).

1. Automatic Escaping

By default, React escapes all variables rendered in JSX. This means that if a user tries to inject a script tag through an input field, React will render it as plain text instead of executing it.

JavaScript

const userInput = '<script>alert("Hacked!")</script>';
return <div>{userInput}</div>; 
// Renders the string literal, does not execute the script.          

2. DangerouslySetInnerHTML

There are times when you genuinely need to render HTML (e.g., from a CMS). React provides dangerouslySetInnerHTML for this, but as the name suggests, it is dangerous.

JavaScript

function MyComponent({ htmlContent }) {
  // ALWAYS sanitize htmlContent before using this!
  return <div dangerouslySetInnerHTML={{ __html: htmlContent }} />;
}          

Note: Use a library like DOMPurify to sanitize HTML before passing it to dangerouslySetInnerHTML.

3. Secure your Props

Be careful when spreading props from untrusted sources. An attacker might try to inject dangerous attributes like onMouseOver or src (for javascript: URLs).

4. Common Security Pitfalls