Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-router-dom (v6) Routing not working in production while working in development

I have defined all my routes in App.js file, given below

<BrowserRouter>
  <Routes>
    {user && <Route path="/dashboard" element={<Dashboard />} />}
    <Route path='/' element={<SignUp />} />
    <Route path='/signin' element={<Signin />} />
    <Route path='/dashboard' element={<Navigate replace to="/signin" />} />
  </Routes>
</BrowserRouter>

The first component is only rendered if there is a user object defined. It defines the path /dashboard and renders the Dashboard component.

The second <Route> component defines the path / and renders the SignUp component.

The third <Route> component defines the path /signin and renders the Signin component.

The fourth <Route> component also defines the path /dashboard, but in this case, it uses the Navigate component to redirect the user to the /signin path. The replace attribute is used to replace the current route in the history stack, and the to attribute is used to define the path to redirect to.

In development it was working fine with all the routing but when deployed to Azure Static Web Apps it is showing 404 page not found. I have attached the image below which is for the URL https://agreeable-coast-05611e900.2.azurestaticapps.net/dashboard

404: Not found page

I have hosted all the projects in GitHub feel free to check it out.

Server - https://github.com/Somanyu/finproject-server

Client - https://github.com/Somanyu/finproject-client

like image 647
Protonic Avatar asked Oct 24 '25 16:10

Protonic


1 Answers

[Solution]

The issue was because of the staticwebapps.config.json file which is a configuration file used by Azure Static Web Apps. It contains settings that configure the behavior of the static web app when it's deployed and running on the Azure platform.

As ReactJS is a single-page application (SPA), and all navigation is handled by JavaScript. By default, if a user navigates to a non-existent route, the server would return a 404 error. With this setting, Azure ensures that all navigation requests get rewritten to the index.html file, which will then load the React app and handle the routing.

So you must add navigationFallback config to the staticwebapps.config.json which tells Azure to rewrite all navigation requests to the index.html file, which is the entry point of your React app.

staticwebapps.config.json file

{
  "navigationFallback": {
    "rewrite": "/index.html"
  },
  "globalHeaders": {
    "Access-Control-Allow-Origin": "https://<YOUR PROJECT>.azurewebsites.net",
    "Access-Control-Allow-Methods": "POST, GET, OPTIONS"
  }
}
like image 161
Protonic Avatar answered Oct 27 '25 07:10

Protonic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!