Photo by Hello I’m Nik on Unsplash
You might run into the following error after deploying a single page React site using React Router to Netlify.
Page Not Found
Looks like you’ve followed a broken link or entered a URL that doesn’t exist on this site.
How did the error occur?
React Router handles routing on the client side (browser) so when you visit non-root page (e.g. https://yoursite.netlify.com/else
), Netlify (server-side) does not know how to handle the route.
(As your routes are set up in the root level).
Error Code & Demo
Here is the simplest code using React Router.
And the error occurring on Netlify when you go to https://<netlify domain>/else
directly.
How can we fix it?
Netlify offers a special file, _redirects, which you can add to your code base and let Netlify handle how to handle the URL that is not handled on the client-side.
Netlify documentation has a section, History Pushstate and Single Page Apps, which shows you how to redirect to the root of your SPA URL (but doesn’t mention React Router, as it applies to other client-side frameworks/libraries).
So to fix the issue, we need to create a file named _redirects
to the root of your site with following content.
Change index.html
accordingly to match the SPA root.
Here is the working site.
For more ways & restrictions for redirect, check out the official Netlify documentation.
Resources
- Where I found out the answer - How do you handle frontend routing with Netlify and React Router v4? on Reddit.
- _redirects Netlify documentation for SPA.
- Source code with
_redirects
file. - Source code without
_redirects
file. - Netlify site with _redirects file.
- Netlify site without _redirects file.