If you have a React web app using React router hosted on Netlify, you might run into a "Page Not Found" 404 error page when you refresh or directly load a non root URL.

Screenshot of Page Not Found error thrown by Netlify
Page Not Found 404 error on Netlify

In this post, I will explain why this error happens and how you can fix it.

Why does this error occur?

This error occurs because React router uses client side routing. Client side routing is a technique where Javascript on a single web page is used to emulate the behavior of multiple pages by changing the elements that are displayed within that page. React router also uses the History API to change the address that is shown in the address bar and to intercept the back / forward navigation actions of the browser to show the expected screen.

Web servers and hosting providers like Netlify default to using server side routing where it expects different web pages to exist at each URL that a user tries to access. For example if the user tries to load /about, Netlify will try to serve /about/index.html and will show an error message if that web page does not exist. This behavior causes errors when we use client side routing because the routes that are set up within React router don't exist as separate web pages on the web server. A page can only be shown once the web page that contains the React web app is loaded. (which is usually /index.html or /)

How to fix it?

To fix this error, we need to set up Netlify to return the page with the React web app for every URL that is requested from it. Once the web app is loaded, React router can then read the URL and render the screen that should be shown.

To achieve this behavior, we can use Netlify's rewrites feature. To set it up, we need to create a file called _redirects with no file extension in the folder that Netlify is set up to publish. Netlify automatically determines the publish folder based on the contents of the repository but you can manually change it in the settings if required. If you are using Create React App, the publish folder should be build. If you are using Vite, the publish folder should be dist. In either case, the _redirects file should be placed in the public folder of your project for it to be copied to the publish folder. It should contain the following rule.

/*  /index.html  200

This rule instructs Netlify to serve /index.html for all requests that don't match a file that is actually on the server. So this will not break the loading of web app which often loads separate Javascript and CSS files from the index.html file.

Note that with this configuration, Netlify will stop showing Page Not Found errors since it will return /index.html for all requests. If you want to show a meaningful error message when a user requests an invalid route, you should set up a no match route within React Router.

Prabashwara Seneviratne

Written by

Prabashwara Seneviratne

Author. Lead frontend developer.