skip to Main Content

I’m using react-router-dom. After deployment the app is not working if we refresh the app, throwing an error Not found, but it works fine in the local environment. This happens for every route.

      <Routes>
          <Route path="/" exact element= {<Navigate to="/posts" />} />
          <Route path="/posts" exact element={<Home />} />
          <Route path="/posts/search" exact element={<Home />} />
          <Route path="/posts/:id" element={<PostDetails />} />
          <Route path="/auth" exact element={ <Auth/>} />
     </Routes>

What went wrong and how to fix this. Is it not working because of improper use of react-router-dom?

And here is the deployed app link: Memories-app

3

Answers


  1. Because react-router-dom only maintain clientside routing and not maintain a serverside routing that’s why you need to rewrite your all path to index.html .
    Seems like you hosted on render. Here is their doc how to rewrite path: https://render.com/docs/deploy-create-react-app#using-client-side-routing

    If you use Reach Router or React Router for client-side routing, you will need to direct all routing requests to index.html so they can be handled by your routing library.

    You can do this easily by defining a Rewrite Rule for your static
    site. Go to the Redirects/Rewrites tab for your service and add a rule
    with the following values:

    Source Path /*

    Destination Path /index.html

    Action Rewrite

    Login or Signup to reply.
  2. This error will occur wherever you would try to hit any route separately. The reason behind this is that render looks for file /posts which is not present.
    For your case, you may resolve it by adding redirect/rewrite rules as below:
    setting up rules

    Login or Signup to reply.
  3. The same happens to me when I used to host my React application. I used to make _redirects file in the same directory as index.html inside the public folder. And paste the below code:

    /*    /index.html   200
    

    This works for me.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search