Fixing 404 Page Not Found Error on Non-Root Route Reload in React
When deploying a React app with client-side routing to a static hosting service like Netlify, you may encounter a 404 error when reloading pages other than the homepage. This error occurs because the hosting service cannot find the specified route on the server.
Creating the _redirects
File
To resolve the 404 error when reloading pages other than the homepage on Netlify, you can configure a _redirects
file to redirect all requests to your index.html
file. Here's how you can do it:
Create a file named
_redirects
in your public folder (next to yourindex.html
file). If the public folder doesn't have one, create a new file with that name.Add the following line to the
_redirects
file:/* /index.html 200
This tells Netlify to serve the
index.html
file for all requests, which allows React Router to handle the routing on the client side.
Including the _redirects
File in Build Output
Make sure that the _redirects
file is included in your build output (e.g., by configuring your build tool to copy it to the build folder). Here are a few steps you can take:
Update your
package.json
scripts to include a copy command for the_redirects
file."scripts": { "build": "react-scripts build && npm run copy-redirects" "copy-redirects": "cp _redirects build/" }
In this example, the
copy-redirects
script is executed after thevite build
command in thebuild
script.
With this setup, the copy-redirects
script will be executed after the build process, ensuring that the _redirects
file is copied to the build
/ dist
directory (or whatever your build output directory is named). This approach keeps your build command cleaner and separates the copy operation into its own script for better maintainability.
Deploying Your App to Netlify
Deploy your application to Netlify. With this configuration, reloading any page on your site should work correctly, and you shouldn't see the 404 error any more.
Troubleshooting
If the error still exists check the deploy log on netlify. If you encounter the error message "A _redirects
file is present in the repository but is missing in the publish directory 'dist'," it indicates that the _redirects
file is present in your repository but is not being included in the publish directory (dist in this case) during the build process. To resolve this, you need to ensure that the _redirects
file is copied to the dist directory during the build process.
Conclusion
By following these steps, you should be able to resolve the 404 error when reloading pages other than the homepage on Netlify. This configuration allows React Router to handle the routing correctly on the client side, ensuring that your app functions as expected.