reactjsreact-router-domvitenetlify

Routes not working properly in React using Vite (ON BUILD)


On my website, I have a few routes that are made using React-Router, that point to a few different pages on the website itself. It all works fine in Development mode, but the build version is where the problems occur. When I upload my webiste to Netlify to test it, the index page (path="/") works fine, but other pages (say for example the about page (path="/about")) throw a 404 error when I refresh them. I have also tried using a different hosting provider but on some it didn't even load the index page, or it did, but not the other pages.

Upon some further research and reading through the Vite documentation, I found that the problem might be that I don't configure Vite, to check for the routes, but I don't know how to do that (or at least properly).

I should also mention that I am quite new to React, so I am sorry if the question is not well put.

Here is the code for the router in the app.js file:

function App() {
  return (
    <>
      <Suspense fallback={<RhombLoad />}>
        <Router>
          <Header />
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/storitve" element={<Storitve />} />
            <Route path="/onas" element={<Onas />} />
            <Route path="/reference" element={<Reference />} />
            <Route path="/zaposlovanje" element={<Zaposlovanje />} />
            <Route path="/kontakt" element={<Kontakt />} />
            <Route path="*" element={<ErrorPage />} />
          </Routes>
          <Footer />
        </Router>
      </Suspense>
    </>
  )
}

I have tried with re-ordering the router, but that didn't seem to change anything...


Solution

  • I was also having same issue, and I even asked it here Netlify and React Vite: Netlify says "Page not found" upon reloading in Vite and React site, Go and check out on this link the first answer helped me out.

    Here's what needs to be done.

    1 - Create _redirects file in the public folder on your project root directory (not in the dist directory).

    2 - Keep the exact following content in the _redirects file: /* /index.html 200.

    3 - Now run the build command and deploy it on the netlify.

    This has worked for me.