Error 404 page not found: How to resolve error 404 page not found in React application when the actual page exist.

Error 404 page not found: How to resolve error 404 page not found in React application when the actual page exist.

The error 404 page not found is a very common theme in single page applications (SPAs) like ReactJS. The problem always arises when you try to navigate to a different page that is not the index page through the url bar or you have navigated to another page through the internal links and then you try to refresh the current page.

When I say you try to navigate to a page that is not the index page, it might seem conflicting because React applications only have one index.html file which is why it is called SPA. But with packages like React Router, they offer the ability to mimic multipage applications by providing an internal linking system.

When we are working on a dev environment, everything seems to work fine until we deploy to a production environment and the application starts breaking.

Understanding the problem.

Let's assume your React application has three (3) pages, when I say pages I mean routes created by packages like React Router. Let's say you have a: home route, an about route and a contact route.

When you visit your domain, for example, you enter mydomain.com in the URL bar, the server serves the index.html which is the only html file you have then you can visit other routes through the internal links you have provided and there won't be any issue.

The problem arises when you try to navigate to other routes through the URL bar, for example, you are trying to navigate to mydomain.com/about. What happens is that the server will try to look for an about.html file that doesn't exist and when the server can't find it, it returns the error 404.

Solution.

If you are deploying your React application on a platform like netlify, there are two ways to solve this problem.

If you are deploying through the GUI, create a file "_redirects" in the public folder and add the following text;

/*    /index.html   200

If you are deploying through the netlify cli then go to the netlify.toml file and uncomment the lines under the [[redirects]] line

If you are deploying your React application on an Apache server then create a .htaccess file in the public folder if it doesn't already exist and add the following

    Options -MultiViews
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.html [QSA,L]

And there you have it.

Conclusion.

In this article, we have discussed how to resolve the error 404 page not found for single page applications like React. I hope you enjoyed reading through it.