7 Best Ways to Prevent Directory Traversal Attack in React.js
Directory traversal attack in React.js is one of the most overlooked yet dangerous vulnerabilities that can lead to unauthorized access to sensitive server files. In this blog, we’ll explore how these attacks occur in a React.js environment, share multiple coding examples, and provide actionable methods to prevent them. Whether you’re using React.js as a frontend or in full-stack applications, understanding this vulnerability is crucial for building secure web applications.
What is a Directory Traversal Attack?
A directory traversal attack, also known as path traversal, is a type of attack that allows attackers to access restricted directories and files on a server by manipulating file paths. In a React.js application, especially when used with Node.js or Express.js for backend handling, improperly validated input paths can lead to serious security breaches.
Example of Malicious Input:
http://example.com/api/files?path=../../../../etc/passwd
This request attempts to access sensitive OS files by navigating up the directory tree using ../
.
How Directory Traversal Attack Happens in React.js
While React.js itself is a frontend framework and doesn’t directly handle file systems, many developers use it alongside APIs (e.g., Express.js) where React passes query parameters or dynamic paths to the backend. If the backend fails to sanitize these inputs, it opens the door for directory traversal attacks in React.js applications.
🔥 Real-World Coding Examples of Directory Traversal in React.js
🔧 Example 1: React Request Vulnerability
// Vulnerable fetch call in React
fetch(`/api/readFile?path=../../../../etc/passwd`)
.then(response => response.text())
.then(data => console.log(data));
If the backend doesn’t sanitize the path, it can expose critical server files.
🔧 Example 2: Insecure Node.js Backend
// Insecure Express.js endpoint
app.get('/readFile', (req, res) => {
const filePath = path.join(__dirname, req.query.path);
res.sendFile(filePath);
});
This code directly appends user input to a directory path, allowing malicious traversal.
✅ Best Practices to Prevent Directory Traversal Attack in React.js
1. Whitelist Allowed Paths
const allowedFiles = ['file1.txt', 'file2.txt'];
if (!allowedFiles.includes(req.query.path)) {
return res.status(403).send('Access Denied');
}
2. Use Path Normalization
const requestedPath = path.normalize(req.query.path);
if (!requestedPath.startsWith('/safe/directory')) {
return res.status(403).send('Invalid Path');
}
3. Avoid User-Controlled File Paths Altogether
Use pre-defined routes or file identifiers instead of raw file paths:
const fileMap = {
'file1': '/safe/files/file1.txt',
'file2': '/safe/files/file2.txt'
};
const safePath = fileMap[req.query.fileId];
res.sendFile(safePath);
🔐 Use Security Tools to Detect Vulnerabilities
Our website vulnerability scanner can detect directory traversal vulnerabilities within seconds. Here’s an actual report screenshot from our tool:
📸 Screenshot: Free Website Vulnerability Scanner Tools
📸 Screenshot: Vulnerability Assessment Report to check Website Vulnerability
Related Blogs You Should Read
If you’re focused on React.js security, check out our previous posts:
- 🔗 Prevent XXE Injection in React.js
- 🔗 Broken Authentication in React.js
- 🔗 File Inclusion Vulnerability in React.js
- 🔗 Fix Broken Authentication in TypeScript ERP
Also, don’t miss our Laravel-focused guide on API Vulnerabilities in Laravel.
🚀 Secure Your Web Apps with Our Penetration Testing Services
If you’re serious about protecting your web applications from threats like directory traversal attack in React.js, our team can help with professional-grade Web App Penetration Testing Services.
Why Choose Us?
- ✅ OWASP Top 10 Coverage
- ✅ Detailed Reporting
- ✅ Affordable Pricing
- ✅ Fast Turnaround
Let us help you identify and fix what automated tools often miss.
Final Thoughts
Directory traversal attack in React.js is not just a backend issue — insecure frontend practices often lead to backend exposure. Developers must sanitize input paths, normalize directories, and avoid relying on user-controlled file references. Integrating security scanners for a Website Security check like ours in your CI/CD pipeline will give your web applications a significant security edge.
Want to secure your app? Contact us now and get started with expert vulnerability testing tailored for React.js applications.
Pingback: Prevent File Inclusion Vulnerability in React.js 7 Best Ways