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
- Never use
dangerouslySetInnerHTMLwith untrusted content. - Validate and sanitize URLs, especially
javascript:schemes inhref. - Implement a Content Security Policy (CSP) to restrict script sources.
- Keep dependencies updated and audit them with tools like Snyk or npm audit.
- 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
httpOnlycookies when possible instead oflocalStorage. - Review third-party components that inject scripts or styles.