DEV Community

Cover image for Fixing Routing Issues in Vite React App on Vercel
pwnkdm
pwnkdm

Posted on

Fixing Routing Issues in Vite React App on Vercel

Deploying a Vite React app on Vercel is straightforward, but many developers face a common issue: navigating to another page and refreshing results in a 404 error. This happens because Vercel serves only index.html and doesn't recognize client-side routing handled by React Router.

The Problem

When using React Router, routes are managed on the client-side. However, Vercel doesn’t know how to handle these routes after a refresh, leading to a 404 error.

The Solution: Configure vercel.json

To fix this, create a vercel.json file inside your frontend root directory (same level as index.html) and add the following:

{
  "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }]
}
Enter fullscreen mode Exit fullscreen mode

Explanation of vercel.json

  • rewrites: Defines URL rewriting rules.
  • source: "/(.*)" captures all routes.
  • destination: Redirects all requests to index.html, allowing React Router to handle routing.

Deploy Again

After adding vercel.json, redeploy your Vite app using:

vercel --prod
Enter fullscreen mode Exit fullscreen mode

Now, navigating and refreshing pages will work without 404 errors. 🎉

This simple fix ensures your Vite React app works smoothly with React Router on Vercel. Happy coding! 🚀

Top comments (0)