So you’ve built a React Single-Page-Application (SPA) with React Router and deployed it on GitHub Pages. Initially, everything looks good on the homepage, but once you try navigating to other routes, a 404 error pops up. You’re left puzzled – it worked perfectly on your local machine! You’ve tried refreshing, incognito mode, even checking GitHub Actions for errors, but the issue persists.
Here’s the deal:
- GitHub Pages doesn’t support client-side routing out of the box unless all routes are children of
/
. - Solutions, do either of the following:
- Use HashRouter, or
- Make all routes children of
/
, (Note: This may not solve the problem properly, and may still result in 404 if the user refreshes the page on a sub-route) or - Consider deploying elsewhere, like Vercel
Note: Deploying a serverless web app on Vercel may encounter a bug where routes other than index don’t work. To fix it, create a vercel.json
at the root of the project (Source):
{
"rewrites": [{ "source": "/(.*)", "destination": "/" }]
}