Solving 404 Errors on Sub-Routes in React + Vite with react-router-v6
So, you’ve just deployed your React + Vite project on Vercel, and everything seems to be working fine until you hit refresh on a sub-route. Suddenly, you find yourself facing a 404 error page, scratching your head and wondering what went wrong. Don’t worry; you’re not alone. This issue often arises due to the interplay of client-side routing, server configuration, and the way your React app handles routes.

The Problem
When you navigate from the landing page to a sub-route and hit refresh, the server attempts to fetch the specific route directly. However, client-side routes are typically managed by your React app, and the server may not recognize these routes, leading to a 404 error.
The Solution
Let’s explore some steps to resolve this common issue:
1. Check Your Hosting Configuration
Ensure that your hosting provider, in this case, Vercel, is set up to serve the same `index.html` file for all routes. This is crucial for client-side routing to work as expected.
2. Use HashRouter
Consider switching from BrowserRouter to HashRouter, especially if you don’t have control over server configuration. HashRouter uses the hash portion of the URL to handle routing on the client side, which can mitigate the sub-route refresh problem.
Install `react-router-dom` version 6:
npm install react-router-dom@6
Use HashRouter in your `index.js` or `App.js`:
import { HashRouter as Router } from 'react-router-dom';
ReactDOM.createRoot(document.getElementById('root')).render(
<Router>
<App />
</Router>
);
3. Configure Server for SPA Mode
Ensure that your server is configured to redirect all requests to your `index.html` file. For Vercel, create a `vercel.json` file with the following configuration:
{
"rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
4. Check Base URL in BrowserRouter
If you are using BrowserRouter, set the `basename` prop to the subdirectory your app is deployed in:
<BrowserRouter basename="/subdirectory">
{/* Your routes go here */}
</BrowserRouter>
5. Adjust Route Configurations
Double-check your route configurations in your React components to ensure they match the paths you are navigating to.
Conclusion
By following these steps, you should be able to overcome the 404 errors when refreshing on sub-routes in your React + Vite project. Remember, understanding the interplay between client-side routing and server configuration is crucial for seamless deployment. Happy coding!