Best 7 Ways to Prevent Cross-Site Scripting in React.js
Introduction: What is Cross-Site Scripting in React.js?
Cross-Site Scripting (XSS) is one of the most notorious and widely exploited web vulnerabilities. In the context of React.js, XSS attacks occur when malicious JavaScript code is injected into a React-based application and executed in a user’s browser.
Although React offers automatic escaping of content by default, developers often bypass this protection—intentionally or unintentionally—resulting in XSS vulnerabilities. This blog post will help you understand the ins and outs of XSS in React, how it happens, how to prevent it, and what tools and practices to adopt for robust security.
How XSS Impacts React Applications
XSS attacks in React can lead to:
- Unauthorized access to sensitive data like session tokens or credentials
- Redirection to malicious or phishing websites
- DOM manipulation and UI spoofing
- Data tampering or exfiltration
If not mitigated, XSS attacks in React apps can destroy user trust, compromise business logic, and violate data protection regulations like GDPR or CCPA.
Common Types of XSS in React.js
- Reflected XSS: The malicious script is reflected off a web application to the user’s browser, typically via URL parameters.
- Stored XSS: The script is stored on the server and served as part of the page, like in a comment section or user profile.
- DOM-based XSS: Occurs entirely on the client side and results from insecure JavaScript operations manipulating the DOM.
Screenshot of our website vulnerability scanner detecting a reflected XSS vulnerabilities:
7 Ways to Prevent Cross-Site Scripting in React.js
1. Avoid Using dangerouslySetInnerHTML
React escapes values by default, protecting against XSS attacks. But using dangerouslySetInnerHTML
overrides that protection.
❌ Vulnerable Example:
const UnsafeContent = ({ userInput }) => (
<div dangerouslySetInnerHTML={{ __html: userInput }} />
);
This opens the door to script injection:
<script>alert('Hacked!')</script>
✅ Secure Alternative Using DOMPurify:
import DOMPurify from 'dompurify';
const SafeContent = ({ userInput }) => {
const clean = DOMPurify.sanitize(userInput);
return <div dangerouslySetInnerHTML={{ __html: clean }} />;
};
Using libraries like DOMPurify ensures only safe HTML is rendered.
2. Use JSX Safely (Let React Do Its Job)
React automatically escapes content passed into JSX, making this safe:
const Comment = ({ text }) => <p>{text}</p>;
Even if text = "<script>alert('XSS')</script>"
, React will escape it and render the string, not execute the script.
3. Validate and Sanitize Inputs
Whether you’re handling form data or query strings, always sanitize and validate user input before rendering it in the DOM.
Example – User Input:
const sanitizeInput = (input) =>
input.replace(/</g, "<").replace(/>/g, ">");
const UserMessage = ({ message }) => (
<p>{sanitizeInput(message)}</p>
);
Also, use a backend sanitizer like xss-clean
for full-stack protection.
4. Use HTTP Headers and CSP
A Content Security Policy (CSP) can prevent malicious scripts from running even if injected.
Example CSP Header:
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none';
You can add this via server config or in Express.js:
const helmet = require("helmet");
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"]
}
}));
Example of a vulnerability assessment report generated using our tool to check Website Vulnerability:
5. Regularly Audit Your Dependencies
React applications depend heavily on third-party libraries, which can be vulnerable themselves.
Useful tools:
npm audit
yarn audit
Snyk
(https://snyk.io)
Run regular scans and update outdated or vulnerable packages.
npm audit fix
6. Use Security-Focused Libraries
Here are some libraries that help reduce the risk of XSS in React:
Library | Purpose |
---|---|
DOMPurify | HTML sanitizer |
helmet | Sets secure HTTP headers (backend) |
xss-clean | Sanitize user input on the backend |
validator.js | Input validation utility |
7. Train Developers & Enforce Secure Code Reviews
Security isn’t just about tools—it’s a mindset. Conduct training, set secure coding standards, and include security checks in your CI/CD pipeline.
Use static analysis tools like ESLint with security plugins:
npm install eslint-plugin-security --save-dev
And add to .eslintrc
:
{
"plugins": ["security"]
}
🔗 Helpful Internal & External Resources
Explore more security topics on our blogs:
- 🛡️ SQL Injection (SQLi) Prevention in React.js
- 💾 Web Cache Deception in TypeScript Apps
- 🔐 Preventing IDOR in RESTful APIs
- 🧰 Directory Traversal in Laravel
- ✉️ Need help? Contact our experts
✅ Conclusion
While React offers solid protection against XSS attacks out of the box, developers still need to remain vigilant. Always validate and sanitize input, avoid dangerous APIs, use CSP and proper headers, and secure both client and server sides.
Protect your web app today—run a free scan for Website Security check and download your full vulnerability report to patch any weaknesses before attackers find them.