How to prevent XSS and secure a React application

· Category: React

Short answer

React escapes text content by default, but XSS can still occur through dangerouslySetInnerHTML, unsafe URLs, and vulnerable dependencies.

Steps

  1. Never use dangerouslySetInnerHTML with untrusted content.
  2. Validate and sanitize URLs, especially javascript: schemes in href.
  3. Implement a Content Security Policy (CSP) to restrict script sources.
  4. Keep dependencies updated and audit them with tools like Snyk or npm audit.
  5. Use rel="noopener noreferrer" on external links.

Example

// Safe external link
<a href={url} target="_blank" rel="noopener noreferrer">
  Read more
</a>

Tips

  • Enable HTTPS everywhere.
  • Store authentication tokens in httpOnly cookies when possible instead of localStorage.
  • Review third-party components that inject scripts or styles.