Netlify makes it easy to deploy React apps for the world to view your awesome front-end application. Unfortunately, you may encounter the error below after deploying your app on Netlify, especially if your React app makes using of React Router for routing or navigation.
In this article, I will guide you through the steps I took to help resolve this issue. Let's get started
Why the Error
In most cases, the home page of the application will be rendered, however, when you navigate to any other page, it will display the error above.
Routing or navigating in React is normally handled by the React Router, which helps in client-side (browser) routing to achieve a seamless user experience typical of single page applications.
After the app has been deployed on Netlify, it has been hosted on their server, traffic to the site and redirecting visitors to other pages will be handled by the Netlify server.
The challenge is, when you visit a non-root page (e.g yoursitename.netlify.com/page), Netlify does not know how to handle the route because we initially performed our routing using React Router (which helps in client-side routing)
How to fix the Error
To enable visitors to easily navigate to other pages of your application, we need to define some rules in the site's _redirects file.
Follow the steps below to add the rules.
Fix 1 : Adding Redirects Rules
Go to the public folder of your application
Create a _redirects file in the public folder (be sure not to add any file extension to it)
- Go into your _redirects file and paste the following code into it
/* /index.html 200
- Save your file run npm run build to build your files again, and redeploy your app on Netlify
The steps below should fix the issue, after the redeployment is complete, you can visit any other page, and you are guaranteed a rendering of the page.
Fix 2: Adding netlify.toml file
In some cases, the above cannot fix the issue, you might even see the error both on the home page, and when you visit other pages.
In that case, follow these steps
- Add a netlify.toml file to the root directory of your project.
- Paste the following code into the file
[[redirects]]
from = "/*"
to = "/"
status = 200
- Redeploy your app to Netlify
Understanding Rewrites
Assigning an HTTP status code of 200 to a redirect rule, makes it a rewrite. This maintains the URL in the visitor's address bar, while Netlify's servers fetch the new location behind the scenes
Conclusion
These are the steps I took to resolve the "Page not found" error after deploying my app on Netlify. Give it a try and let me know if it fixes your issue.
Have a productive day