Adding a web.config to deploy a react app to IIS
You have a react project and you want to deploy it on an Azure App Service which runs IIS or any other IIS powered website. Your react app uses react-router and has some client side URLs in your project.
Everything is working fine, until you think of hitting the refresh button and at that point you get a HTTP 404. Which is normal because on the server those urls/pages don’t exist, they are only on the client. When refresh is hit the browser goes and asks that page from the server, the server tries to locate it and because there is nothing there a 404 response is returned. You start reading on the issue and you find out about URL Rewrite and ways to import URL Rewrite Rules.
Step by step you find out that a web.config file with such rewrite rules should be deployed to the Azure App Service. And I will show you 2 ways how you can add a web.config file to your react project and how your file will get to be part of the app bundle.
Here is an example of a web.config file with rewrite rules, which you can use in your project.
This is the simple solution and it involves adding the web.config file side by side with your source files and find the way to make it part of the bundle. It will only work for webpack, if you are building with react-scripts you can go the Second way directly.
import "./web.config";
and this will mark the fact that this file is being used.
3. For webpack we will need to tell it what to do with the web.config file, because if you run at this moment you will get a similar error:
Module parse failed: …src\web.config Unexpected token (1:0)
So in your webpack.config.*.js add the line below in the module, rules section, which will tell the webpack file loader that the web.config should be treated as a file in the output:
{test: /\.(config)$/, loader: ‘file-loader?name=[name].[ext]’}
With react-scripts you don’t have any configuration file, so we can’t have that 3rd step where we were using the file-loader. Instead here we will add an additional build step, which allows us to make a better separation between the code and the configuration and deploy. This second way of doing things works both for webpack and react-scripts.
“postbuild”: “node iisConfig/copyIISConfig.js”,
3. This can also be used for webpack, just modify the webConfigPath variable from the copyIISConfig.js file, so it gets copied to the dist folder, instead of the build one.
So now just execute npm run build and inside the output folder (build or dist) you will have the web.config file. And this makes the bundle ready to deploy to an IIS website.