Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

404 Error on refresh with SPA React Router app in GitHub Pages

I built my website with React and React Router and it is hosted on Github Pages. When I refresh the site on a page that is not my home page OR do ctrl+click to open the page in a new tab, it leads to a 404 error. I know this is because Github pages doesn't have access to front-end routes and one solution is to add a 404.html file that redirects back to your index.html.

I tried following the instructions on both

  1. https://github.com/websemantics/gh-pages-spa
  2. https://github.com/rafgraph/spa-github-pages

but neither worked for me. I think I am missing something but I can't figure out what is going wrong as I'm not that familiar with React Router. Can anyone help? (Note: I know a solution is to use HashRouter but I don't want my URLs to look ugly)

My code can be viewed on GitHub: https://github.com/christinexlin/portfolio

like image 381
Christine Avatar asked Aug 18 '20 06:08

Christine


People also ask

How do I fix 404 error on GitHub?

If you saw 404 even everything looks right, try switching https/http. The original question has the url wrong, usually you can check repo settings and found the correct url for generated site.

How do I fix error 404 in React?

An alternative way to handle 404 page not found in React router is to redirect the user to a different page when they try to go to a page that doesn't exist. Copied! In the example, instead of rendering a PageNotFound component, we redirect the user to / if they go to a route that doesn't exist.

Can I use React router in GitHub Pages?

So now we can deploy our react-router app to Github pages. You can refer to this GitHub repository for the deployment. Just make sure your homepage URL (project repository name) in package. json is the same as the homepage path.


Video Answer


2 Answers

I've spent quite some time to fix this issue. The issue is that GitHub Pages doesn't support single page apps, so there is a 404 error when refreshing page.
Check this out https://github.com/rafgraph/spa-github-pages and follow instructions, it is pretty straightforward. I've followed "basic instructions", but take a look at step 5 in "detailed instructions", that helped me fix it completely (adding repo name to absolute path of assets in index.html and setting segmentCount to 1).
Take a look at my code https://github.com/milosrancic/reactjs-website . I haven't used HashRouter, I've used Switch. And also I've added 404.html file.
I hope this helps

like image 163
Milos Rancic Avatar answered Oct 22 '22 15:10

Milos Rancic


To get this to work, all I did was add a step to my GitHub Pages deploy pipeline that copies index.html to 404.html and then let my router handle the rest.

Note that this will still result in the routes returning a 404 status so SEO or CLI pings will think that requests failed.

like image 27
electrovir Avatar answered Oct 22 '22 17:10

electrovir