January 17, 2024 07:01 by
Peter
Have you ever seen a blank screen or 404 error when trying to reload a page in a React Router-powered application? This happens when there are no defined routes in the application's routing setup that match the URL path.
Note: I've been having trouble with this and have since figured out a solution, so this is only for Windows server hosting.
This is happening as a result of the Single Page Application (SPA) that your website is built on React. Your application, index.html, loads automatically when you access the website through the root directory. and hence you never truly leave the index.html page even when you navigate to other pages.
Make sure the URL Rewrite module is enabled in your server setup. You can change or rewrite the URLs with this module.
- Go to Control Panel -> Programs -> Programs and Features.
- Click on "Turn Windows features on or off" on the left sidebar.
- Scroll down and locate "Internet Information Services," expand it, and then select "World Wide Web Services" -> "Common HTTP Features" -> "URL Rewrite."
- Click "OK" and let the feature be installed.
Once the URL Rewrite module is enabled, open your project's web.config file (located in the root directory of your application).
<system.webserver>
<rewrite>
<rules>
<rule name="React Router" 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="/" />
</rule>
</rules>
</rewrite>
</system.webserver>
Note: Before using the aforementioned technique, make sure your React application is developed and deployed correctly on the Windows server.