Reputation: 513
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.
Upvotes: 14
Views: 9027
Reputation: 535
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
On Azure Static Webapp add this file to the base directory of your project staticwebapp.config.json
and add the following contents
{
"navigationFallback": {
"rewrite": "/index.html"
}
}
You can learn more about it here https://learn.microsoft.com/en-us/azure/static-web-apps/configuration
Upvotes: 2
Reputation: 1
This below snippet works for me. You just need to create _redirects
inside public folder.
/* /index.html 200
After completing above steps use vercel --prod
to deploy on vercel. That's it.
Thank to @Zayne komichi
Upvotes: 0
Reputation: 513
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" }]
}
Upvotes: 36