Search code examples
reactjsreact-routernetlifyvercelvite

Vite.js React Build Not Redirecting On Netlify And Vercel


I made a react build with vite.js. When building for production and testing on local host all is working fine. But when i deploy to Netlify or vercel routes that i created with react-router are not accessible via entering their url directly, but only from the main page ('/') via using the links inside of the application.

If i click on the route link in the application the route is working, but if i enter the url directly (for example: mypage/about) i am getting a 404 error.

I checked in with vercel support and they said that likely a redirect is missing in the configuration, which is for example setup by default by create-react-app. In CRA it looks like this

{
  "redirects: [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}

After going through the vite.js documentation i can't find any hints on how to setup a redirect in vite.


Solution

  • This is not a problem with vite.js but due to with a missing configuration file for vercel which is added by default to the existing templates. For a single page application the html files for the routes created with react router don't exist, so something on the server needs to create rewrites to make sure every request points at '/' or index.html. In Vercel this can be done by adding a rewrite to config file in the root of the project called

    vercel.json
    

    https://vercel.com/docs/configuration Add rewrites for all routes to the file that point to '/' or '/index.html'

    {
      "rewrites": [{ "source": "/(.*)", "destination": "/" }]
    }
    

    or

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