Jim
Jim

Reputation: 2828

Urls don't work on refresh withing React app hosted on Azure

I have just noticed that in my react app the urls don't work when user refreshes the page. The weird things is that locally everything works fine. I have created the app using create-react-app. I was reading the React-router urls don't work when refreshing or writing manually but since the build process is run automatically through github actions it is not clear how to solve this. Can anyone suggest a quick solution?

Upvotes: 0

Views: 5546

Answers (5)

msi95
msi95

Reputation: 1

I just solved this issue today -- if you are using an Azure Storage account with the 'static website' option enabled (under Data Management -> Static Website), then just make sure that your Index document name and error document path both point to index.html.

Previously, it was pointing to error.html, and causing the site to break on refresh or manual URL entry. Since the 'error' now redirects to index.html anyway, it will then get picked up by the router. This is a band-aid solution but if you are just trying to fix it for the time being, this will likely work. If you are handling error/404 client side, then the only downside to this seems to be that you still have a 404 console error msg.

Upvotes: 0

You need to add this code into you build folder of your react app with file name web.config

<?xml version="1.0"?> 
<configuration> 
<system.webServer> 
<rewrite> 
<rules> 
<rule name="React Routes" stopProcessing="true"> 
<match url=".*" /> 
<conditions logicalGrouping="MatchAll"> 
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> 
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> 
<add input="{REQUEST_URI}" pattern="^/(api)" negate="true" /> 
</conditions> 
<action type="Rewrite" url="/" /> 
</rule> 
</rules> 
</rewrite> 
</system.webServer> 
</configuration>

And that's all you need to do. This will solve your problem of refresh on your links

Upvotes: 0

Dhanushka Rukshan
Dhanushka Rukshan

Reputation: 657

Add this file

routes.json

with the below code

{
  "routes": [
    {
      "route": "/*",
      "serve": "/index.html",
      "statusCode": 200
    }
  ]
}

Upvotes: 1

Jim
Jim

Reputation: 2828

The answer to the problem is fallbackroutes found on this page https://learn.microsoft.com/en-us/azure/static-web-apps/configuration. Add staticwebapp.config.json at the root folder of your react app with the below content and push to git:

{
  "navigationFallback": {
   "rewrite": "/index.html"
  }
}

Upvotes: 8

justpen
justpen

Reputation: 296

I had the same problem with GitHub pages and this is because the routes don't exist on the server and are handled by the frontend router.

I solved it by replacing the 404 page with my index.html. The index.html will load in react-router which in turn will handle the routing.

You could try to replace or redirect the Azure 404 page to your index.html.

Upvotes: 2

Related Questions