How do you deploy a published React application to Azure and support React Router, too?

Posted: (EET/GMT+2)

 

Let's say you've developer a React front-end application, and your task is to get it running on Azure. For a typical React application created with Create-React-App tool (often abbreviated CRA), deployment to Azure is just publishing the static build output. The interesting part is getting React Router working so that direct links to routes do not return HTTP 404 errors.

Here are a list of steps you can use.

1) Build the production version of your React application:

npm run build

This creates a build folder with index.html, JavaScript and CSS files. These are the files you need to run your application.

2) Deploy the contents of build to an Azure App Service (for example, via FTP, Web Deploy, or from a CI build).

3) Add a web.config file in the build output to rewrite all non-file requests back to index.html. This lets React Router handle the route on the client side.

<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="ReactRouter" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

With this configuration in place, a request to /products/42 will return index.html, and React Router can render the correct view. Static assets like scripts and images are still served directly.

If you prefer not to use URL rewriting, an alternative is to use HashRouter in React, but the rewrite approach keeps your URLs cleaner.