Sharon
Sharon

Reputation: 3909

Why does my React app work locally but not on Azure?

I've made a web app in ReactJS. It runs fine on localhost. However, when I deploy to Azure, I'm getting 404 errors every time I navigate to a new page or if I reload a page.

I'm using BrowserRouter, and I've gathered from looking online that this sometimes causes issues, but I haven't found a way to fix it.

I have the app in GitHub, so in Azure I link to the repository. As well as the code generated by create-react-app, I have a web.config file which contains:

<?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>

So my GitHub code has package.json & web.config files, and src & public folders. This is what gets copied to wwwroot in Azure.

I've set up a pipeline which runs the following:

I've read various things online, which have suggested using a static build, or uploading the 'build' folder, creating a production build, or configuring the serviceWorker, but I've tried out all the things that I came across, and nothing has made any difference.

I've defined the route USEROVERVIEW = '/dashboard/users/:patientId'; but when I try to navigate to it on Azure, I get a 404 error. On the other hand, I can navigate to 'landingpage' and 'dashboard' with no problem - it seems to be the routes with ':' which are the problem.

I'm not overly familiar with React or Azure, so I don't know where to start looking.

Upvotes: 1

Views: 2379

Answers (1)

Sharon
Sharon

Reputation: 3909

OK, I solved this after following Ajeet Shah's link above.

The issue seems to be that I'm using BrowserRouter within my app. I don't know why this caused an issue, but it seems to. So, instead, I decided to deploy a static version of my app to Azure Storage.

I created the static build using

npm run build

and was able to start it locally using

serve -s build

(had to do npm install -g serve to make this work). This let me run it locally as a static site, so I could see that it was working (note: if I started it using serve build (without the -s flag) then the rerouting etc didn't work, the flag had to be there).

I then followed this to set up a static website on Azure Storage.

I use VSCode, and installed an extension called Azure Storage which lists all your Storage Blobs, so I opened my code in VSCode, found the appropriate blob, right clicked, and selected "deploy". It worked fine first time.

Upvotes: 1

Related Questions