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

5

19

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

Kristof answered 18/8, 2020 at 6:13 Comment(1)
T
15

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

Tzar answered 19/8, 2020 at 17:53 Comment(0)
F
4

I also have the same issue and waste a lot of time to fix it, but when I found that the solution is just on keywords i was surprised, so here is the solution:

goto your react project where you have defined your routes and replaced BrowserRouter with HashRouter.

In my case, I have defined routes in this way

Before Error Resolve

src/index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { BrowserRouter} from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>
);

After Error Resolve

After Replacing BrowserRouter with HashRouter it works fine for me and the code after changes is like this:

src/index.js:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { HashRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <HashRouter>
        <App />
    </HashRouter>
);
Formaldehyde answered 10/8, 2022 at 7:11 Comment(1)
This indeed fixed my issue. Thanks.Tude
C
3

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.

Claritaclarity answered 24/9, 2021 at 1:56 Comment(0)
F
0

One way you can try to fix this is by replacing Switch with HashRouter in your App.js . This will change your URLs, but it should fix your 404 issue for github pages. If you need a more in depth explanation of why this happens read this reply.

So your updated App.js should look like this:

import React, { Component } from "react";
import { HashRouter, Route } from "react-router-dom";
import Emoji from "react-emoji-render";
import "./App.css";
//Pages
import Projects from "./Projects.js";
import About from "./About.js";
import Critterpedia from "./Critterpedia.js";
import Bluenotes from "./Bluenotes.js";
import Formally from "./Formally.js";
//Components
import visualize from "./Images/visualize-actualize.png";
import ScrollToTop from "./ScrollToTop.js";

class App extends Component {
  render() {
    return (
      <div>
        <ScrollToTop />
        <HashRouter>
          <Route exact path="/" component={Projects} />
          <Route path="/about" component={About} />
          <Route path="/critterpedia" component={Critterpedia} />
          <Route path="/bluenotes" component={Bluenotes} />
          <Route path="/formally" component={Formally} />
        </HashRouter>

        <div className="footer">
          <div className="emoji">
            <Emoji text="💭" />
          </div>

          <div className="intro-icon">
            <div className="img-div">
              <img src={visualize} alt="visualize and actualize" />
            </div>
          </div>

          <div className="credit">
            <div className="footer-links">
              <a href="https://github.com/christinexlin">GitHub</a>
              <a href="https://www.linkedin.com/in/christine-lin-01/">
                LinkedIn
              </a>
              <a href="https://twitter.com/christinexlin">Twitter</a>
            </div>
            <p>
              Made with <Emoji text="🖤" />
              by Christine Lin
            </p>
          </div>
        </div>
      </div>
    );
  }
}

export default App;

Let me know if this works for you

Flirtation answered 18/8, 2020 at 8:51 Comment(0)
H
0

2 solutions:

  1. Replace "BrowserRouter" with "HashRouter". (just you will find an extra "#" gets added in your base route)
  2. update or create a 404.html file in a public Directory: e.g.
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;700&display=swap" rel="stylesheet">

  <title>Your Title</title>
  <script type="text/javascript">
    var segmentCount = 1;
    var l = window.location;
    l.replace(l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : ''));
  </script>
</head>

<body>
</body>

</html>

I was facing the same issue and resolved it from stackoverflow.com.

Houri answered 8/3 at 5:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.