10

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.

Shantiscrip
  • 363
  • 3
  • 8

2 Answers2

25

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" }]
}
Shantiscrip
  • 363
  • 3
  • 8
  • This solution worked for me, but I had to set destination to `"/"` instead of `"/index.html"` (otherwise, I still get 404 page). – kimbaudi Jul 15 '21 at 23:43
  • Thanks very much. Answer should be accepted as solution. – Benjamin Fourgeaud Dec 07 '21 at 11:03
  • You saved the day bro. I utilized/wasted 3 hours of my night/life finding this answer. btw how do we fix this in heroku, netlify and others? – Circuit Planet Sep 30 '22 at 21:38
  • Thanks @Shantiscrip!! Your soltuion worked like cake. I created a new file in my project folder called "vercel.json" & used your first solution. Thanks a lot! – Subu Hunter Aug 09 '23 at 19:28
1

If you are using vite create a folder called public and add a file called _redirects to it, for the rest of the other bundlers just add the _redirects file to the public folder

put this inside the _redirects file

/* /index.html 200

Link Here - thats the link if you want to see the project structure

Zayne komichi
  • 408
  • 4
  • 11