If you've built a Single Page Application (SPA) with React and React Router, you might have noticed everything works fine locally with npm or yarn. However, after deploying to Netlify, you encounter a "Page Not Found" error when navigating directly to non-root pages (e.g., https://yoursite.netlify.com/login).
Understanding the Issue
React Router handles routing on the client-side (in the browser), while Netlify handles routing on the server-side. When you access a non-root URL directly, Netlify doesn't know how to handle the route, resulting in a "Page Not Found" error.
Solution
To resolve this, Netlify allows you to use a special file called _redirects. This file instructs Netlify to serve the index.html file for all routes, allowing React Router to handle the routing.
Steps to Fix the Error
-
Create the
_redirectsFile: In the root of your site (usually thepublicfolder), create a file named_redirectswith the following content:
/* /index.html 200
-
Deploy Your Site: After adding the
_redirectsfile, build your site and deploy it to Netlify again.
Example
Here is an example of the _redirects file content:
/* /index.html 200
Additional Resources
- Netlify Documentation on History Pushstate and Single Page Apps
- Source Code with
_redirectsFile on GitHub - Live Example Site with
_redirectsFile
By following these steps, your React Router-based SPA should handle client-side routing correctly after deployment to Netlify.
For more detailed guidance, you can refer to the official Netlify documentation on redirects and rewrites.
Happy coding! π




Top comments (0)