When hosting your React application on Vercel, you might encounter a common issue where manually editing the route in the address bar causes a 404 error. This happens because Vercel doesn't automatically handle client-side routing for single-page applications (SPAs). To fix this, you need to configure Vercel to serve your React app for all routes. This can be done by adding a vercel.json
file with specific rewrites.
Understanding the Issue
In a typical React application, routing is handled on the client-side using libraries like React Router. When you navigate to a route like /about
, the browser sends a request to the server, which by default looks for a corresponding file or resource. If none is found, a 404 error is returned. This issue arises because Vercel is unaware that the routing should be handled by the client-side application.
Solution: Using vercel.json
with Rewrites
To ensure that all routes are handled by your React application, you can add a vercel.json
file to your project with a rewrites configuration. This tells Vercel to serve your index.html
file for all routes, allowing the client-side router to take over.
Step-by-Step Guide
Create or Update
vercel.json
In the root of your project, create a
vercel.json
file (or update it if it already exists) with the following content:{ "rewrites": [ { "source": "/(.*)", "destination": "/" } ] }
This configuration ensures that any route requested by the browser will be redirected to the
index.html
file.Deploy Your Application to Vercel
If you haven't already deployed your application to Vercel, follow these steps:
Install Vercel CLI (if you haven't already):
npm install -g vercel
Login to Vercel:
vercel login
Deploy Your Application:
vercel
Follow the prompts to deploy your application. Vercel will detect your React project and apply the necessary configurations.
Verify the Configuration
Once the deployment is complete, navigate to your application's URL and try manually changing the route in the address bar. The React application should handle the routing without returning a 404 error.
Example Project Structure
Here’s an example structure of your project with the vercel.json
file included:
my-react-app/
├── public/
│ └── index.html
├── src/
│ ├── App.js
│ ├── index.js
│ └── ...
├── vercel.json
├── package.json
└── ...
Conclusion
By adding a vercel.json
file with the appropriate rewrites configuration, you can avoid 404 errors when manually editing routes in the address bar of your React application hosted on Vercel. This ensures that all routes are properly handled by your client-side router, providing a seamless user experience.
This simple configuration change allows you to leverage Vercel’s powerful hosting capabilities without running into common issues associated with client-side routing in SPAs. Happy coding!