You'll need to update the basename of your routes so they are valid links. But to do routing like that with fake paths, you need a server to support it. GitHub Pages does not. So you'll want to change to hashes or query parameters instead for your routes. Answer from CreativeTechGuyGames on reddit.com
🌐
GitHub
github.com › orgs › community › discussions › 64096
GitHub Pages does not support routing for single page apps · community · Discussion #64096
Navigating by clicking on links while in the app will work, but going directly to a page's url in the address bar (eg username.github.io/mysite/page1 or mysite.com/page1) will result in a 404 error page as no "page1.html" exists and GitHub pages doesn't have a way for the repo to indicate all requests should go back to the index.html. As far as I can tell from my testing, there are 2 valid workarounds: When using react-router, use HashRouter instead of BrowserRouter.
🌐
Reddit
reddit.com › r/reactjs › how to handle routes in github pages?
r/reactjs on Reddit: How to handle routes in Github Pages?
May 24, 2020 -

I have a react website published on github pages, my hompage and repository is

/websiteName

so it's working when I'm at the hompage, ex:

username.github.io/websiteName

. But I also have a route which is

/user/:id

, so when I click a link it will redirect me to

username.github.io/user/123

thus giving me a 404 error. So how do I fix the 404 error when redirecting to a different route other than

/websiteName

.

Discussions

Can I create routes with react-router for a github-pages site?
Ok, so I've made a SPA using React and React-Router and have pushed it to github pages, but none of the routes I have written work when I refresh or click back in my browser. I had the same problem... More on stackoverflow.com
🌐 stackoverflow.com
BrowserRouter is not compatible within a GitHub Pages deployment
To host the app on GitHub Pages, you need to use the BrowserRouter from the react-router-dom package in the project's root file. More on github.com
🌐 github.com
4
12
My page comes out 404 with routing
This works because the actual page is still just /repo, so GitHub loads the correct page, but the hash router will recognize #/subpage and render the correct visuals. More on github.com
🌐 github.com
2
3
reactjs - React Router v4: Cant load page on GitHub pages - Stack Overflow
Yes if I remove it then the default route / shows the NotFound route and /buttons is still not accessible ... GitHub Pages doesn’t support routers that use the HTML5 pushState history API under the hood (for example, React Router using browserHistory). More on stackoverflow.com
🌐 stackoverflow.com
November 4, 2019
Top answer
1 of 10
72
  1. If deploying to GitHub, ensure there is a "homepage" entry in package.json for where you are hosting it in Github.

    Examples:

    User Page

    "homepage": "https://amodhakal.github.io",
    

    Project Page

    "homepage": "https://amodhakal.github.io/portfolio",
    

    Custom Domain Page

    "homepage": "https://amodhakal.com",
    

    Vite: add the project directory as the base.

    vite.config.js

    export default {
      ...
      base: "/portfolio"
    };
    
  2. Switch to the HashRouter since GitHub pages doesn't support the tech used by the BrowserRouter.

    index

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import { HashRouter } from 'react-router-dom'; // Note 1
    import App from './App';
    import './styles/index.css';
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <HashRouter>
          <App />
        </HashRouter>
      </React.StrictMode>
    );
    

    react-router data routers

    import ReactDOM from 'react-dom/client';
    import App from './App';
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
    
    import {
      createHashRouter,
      RouterProvider
    } from 'react-router-dom'; // Note 1
    // import routed components
    
    const router = createHashRouter([
      ... routes configuration
    ]);
    
    const App = () => {
      ...
    
      return <RouterProvider router={router} />;
    };
    
    export default App;
    

For more details see the create-react-app docs for deploying to GitHub Pages and notes on client-side routing.

1If using React-Router 7 library, all exports are from react-router instead of react-router-dom. Follow the RR7 installation and setup.

2 of 10
17

I faced this similar routing problem in ReactJs when I used gh-pages.

My Problem: Routes are working fine at my local system but when I deployed my web app using gh-pages, I wasn't able to go to the sub-pages directly.

Example: ayushjaink8.github.io/cfhelper was working, and I am able to go to other pages from within the web app. But when I enter ayushjaink8.github.io/cfhelper/dashboard in the URL, it shows the github 404 error page.

Solution: I resolved the above problem by using <HashRouter/> and adding the homepage tag in the package.json like homepage: "/<repository-name>/#".

Note that gh-pages also follows the # rule in its URL routing. So it won't show any 404 error page if you write ayushjaink8.github.io/cfhelper/#/<any-route-of-your-app>.

Everything else remains the same in my codebase. I did not use the useHistory(), <BrowserRouter /> or any other functions. Only using <HashRouter/> works most of the time.

Your homepage becomes /<repo-name>/# instead of /<repo-name>. That's the only thing that change when you use <HashRouter/>.

For example, previously the homepage is: https://ayushjaink8.github.io/cfhelper/ with <HashRouter/>, the URL now becomes: https://ayushjaink8.github.io/cfhelper/#

This also applies to the routes.

Here goes my sample code:

import { Routes, Route, HashRouter } from "react-router-dom";

<HashRouter>
      <Navbar />
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/auth/login" element={<Login />} />
        <Route path="/auth/signup" element={<Signup />} />
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/contests/create" element={<CreateContest />} />
        <Route exact path="/contests/join" element={<JoinContest />} />
        <Route path="/contests/live" element={<LiveContest />} />
        <Route path="/practice" element={ <Practice /> } />
        <Route path="/analyze" element={ <Analyze /> } />
        <Route path="/verify" element={<VerifyEmail />} />
        <Route path="/profile/edit" element={<EditProfile />} />
      </Routes>
      <Footer />
</HashRouter>

Package.json Sample Code:

{
  "name": "cfhelper",
  "homepage": "/<your-github-repo-name>/#",
  "version": "1.0.0",
  "private": true,
}

🌐
GitHub
github.com › rafgraph › react-github-pages
GitHub - rafgraph/react-github-pages: React with React Router boilerplate for GitHub Pages
Also, GitHub Pages are always available at example.tld/my-repo-name, even when a custom domain is in use. Accessing the site at /my-repo-name will cause frontend routing to break, so when the site is accessed at /my-repo-name, a redirect to just the domain with no path is required.
Starred by 49 users
Forked by 11 users
Languages   JavaScript 82.4% | HTML 17.6% | JavaScript 82.4% | HTML 17.6%
🌐
freeCodeCamp
freecodecamp.org › news › deploy-a-react-app-to-github-pages
How to Deploy a Routed React App to GitHub Pages
February 22, 2021 - Why does this happen? Because GitHub Pages does not support browser history like your browser does. In our case, the route https://tomerpacific.github.io/starter-project/about doesn't help GitHub Pages understand where to point the user (since it is a frontend route).
Find elsewhere
🌐
GitHub
github.com › rafgraph › spa-github-pages
GitHub - rafgraph/spa-github-pages: Host single page apps with GitHub Pages · GitHub
This is a lightweight solution for deploying single page apps with GitHub Pages. You can easily deploy a React single page app with React Router <BrowserRouter />, like the one in the demo app, or a single page app built with any frontend library ...
Starred by 4K users
Forked by 573 users
Languages   TypeScript 79.6% | HTML 15.1% | JavaScript 5.3%
Top answer
1 of 1
19

As per deployment docs at https://create-react-app.dev/, for GH pages:

GitHub Pages doesn’t support routers that use the HTML5 pushState history API under the hood (for example, React Router using browserHistory). This is because when there is a fresh page load for a url like http://user.github.io/todomvc/todos/42, where /todos/42 is a frontend route, the GitHub Pages server returns 404 because it knows nothing of /todos/42.

If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions:

  • You could switch from using HTML5 history API to routing with hashes. If you use React Router, you can switch to hashHistory for this effect, but the URL will be longer and more verbose (for example, http://user.github.io/todomvc/#/todos/42?_k=yknaj) Read more about different history implementations of react-router.

Change your routing from:


    <BrowserRouter basename={process.env.PUBLIC_URL}>
      <Route render = {({ location }) => (
         <Layout location = { location }>
             <Switch location = { location }>
                <Route exact path = '/' component = { Home } />
                <Route exact path = '/buttons/' component = { Buttons } />
                <Route component = { NotFound }/>
              </Switch>
           </Layout>
       )} />
    </BrowserRouter>

To:

import { HashRouter, Route, Link } from "react-router-dom";

...


    <HashRouter basename={process.env.PUBLIC_URL}>
      <Route render = {({ location }) => (
         <Layout location = { location }>
             <Switch location = { location }>
                <Route exact path = '/' component = { Home } />
                <Route exact path = '/buttons/' component = { Buttons } />
                <Route component = { NotFound }/>
              </Switch>
           </Layout>
       )} />
    </HashRouter>
...

  • Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your index.html page with a special redirect parameter. You would need to add a 404.html file with the redirection code to the build folder before deploying your project, and you’ll need to add code handling the redirect parameter to index.html. You can find a detailed explanation of this technique in this guide.
🌐
DEV Community
dev.to › janjibdev › problem-with-react-router-app-and-github-pages-lij
Problem with react-router app and Github Pages (Solved !) - DEV Community
August 13, 2021 - Oh, I've forgotten to link the deployment. dilinar.github.io/work_management_... While it does load the home page properly and going to any subpage via the buttons works, trying to refresh any of the subpages results in a 404 error. Also, going back to the home page loads the error page. ... Computer engineering student and a tech enthusiast. ... I just simply wrapped all my routes inside the HashRouter instead of BrowserRouter and it works fine
🌐
DEV Community
dev.to › caffiendkitten › react-router-with-github-pages-en3
React Router with GitHub Pages - DEV Community
March 16, 2021 - Once you have the import statement with the tags you like you can implement the routes tags in your project. For my I placed them in my Header file that will be the navigation of my app like so. The issue is that when you use GH Pages that it has a specific address, your gh name + github.io.
🌐
GitHub
github.com › orgs › community › discussions › 66701
How to implement Angular Dynamic routing on Github Pages · community · Discussion #66701
I have followed this instructions on how to deploy an Angular app on github pages. I have copied the content of index.html in 404.html as said. All the content is displayed and every route works as expected, but Github Pages will still issue a 404 error for every page that is not the main one.
🌐
Stackademic
blog.stackademic.com › deploy-a-react-app-to-github-pages-with-multiple-routes-and-support-protected-routes-f0c70b306b71
How To Deploy a React App to GitHub Pages? | by Balamurugan V | Stackademic
January 15, 2024 - The name of the repository should be following the guidelines (no spaces in-between, should be readable, etc). You can always change the repo name under the settings menu in your GitHub account. Install the required package for routing in react:-
Top answer
1 of 1
6

github pages don't work well for single page application but there is hack around it. add this script to your index.html in public folder

  <script type="text/javascript">
    // Single Page Apps for GitHub Pages
    // https://github.com/rafrex/spa-github-pages
    // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
    // ----------------------------------------------------------------------
    // This script checks to see if a redirect is present in the query string
    // and converts it back into the correct url and adds it to the
    // browser's history using window.history.replaceState(...),
    // which won't cause the browser to attempt to load the new url.
    // When the single page app is loaded further down in this file,
    // the correct url will be waiting in the browser's history for
    // the single page app to route accordingly.
    (function (l) {
      if (l.search) {
        var q = {};
        l.search.slice(1).split('&').forEach(function (v) {
          var a = v.split('=');
          q[a[0]] = a.slice(1).join('=').replace(/~and~/g, '&');
        });
        if (q.p !== undefined) {
          window.history.replaceState(null, null,
            l.pathname.slice(0, -1) + (q.p || '') +
            (q.q ? ('?' + q.q) : '') +
            l.hash
          );
        }
      }
    }(window.location))
  </script>

and create a custom 404.html in public folder

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Single Page Apps for GitHub Pages</title>
    <script type="text/javascript">
        // Single Page Apps for GitHub Pages
        // https://github.com/rafrex/spa-github-pages
        // Copyright (c) 2016 Rafael Pedicini, licensed under the MIT License
        // ----------------------------------------------------------------------
        // This script takes the current url and converts the path and query
        // string into just a query string, and then redirects the browser
        // to the new url with only a query string and hash fragment,
        // e.g. http://www.foo.tld/one/two?a=b&c=d#qwe, becomes
        // http://www.foo.tld/?p=/one/two&q=a=b~and~c=d#qwe
        // Note: this 404.html file must be at least 512 bytes for it to work
        // with Internet Explorer (it is currently > 512 bytes)

        // If you're creating a Project Pages site and NOT using a custom domain,
        // then set segmentCount to 1 (enterprise users may need to set it to > 1).
        // This way the code will only replace the route part of the path, and not
        // the real directory in which the app resides, for example:
        // https://username.github.io/repo-name/one/two?a=b&c=d#qwe becomes
        // https://username.github.io/repo-name/?p=/one/two&q=a=b~and~c=d#qwe
        // Otherwise, leave segmentCount as 0.
        var segmentCount = 0;

        var l = window.location;
        l.replace(
            l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') +
            l.pathname.split('/').slice(0, 1 + segmentCount).join('/') + '/?p=/' +
            l.pathname.slice(1).split('/').slice(segmentCount).join('/').replace(/&/g, '~and~') +
            (l.search ? '&q=' + l.search.slice(1).replace(/&/g, '~and~') : '') +
            l.hash
        );
    </script>
</head>

<body>
</body>

</html>

what this does is that we when refresh the page github actually reaches the server for that specific route but since it's SPA the file won't be available so it send the 404.html page which gets the pathname from the file and calls the index.html page and pastes the pathname there.

🌐
Medium
reginafurness.medium.com › client-side-routing-on-github-pages-with-create-react-app-f5a393341c2
Client Side Routing on GitHub Pages with Create React App | by Regina Furness | Medium
November 22, 2020 - I still had one problem, though, if someone refreshed while they were on a route that wasn’t '/' it would cause a 404 error. So why was I still getting 404 errors on refresh? Well it goes back to the fact that GitHub Pages is hosting your homepage URL but it knows nothing of your client side routing, it doesn’t recognize those routes as being part of the same application.
🌐
Medium
gmfuster.medium.com › deploying-a-react-app-to-github-pages-24c3e5485589
How I finally got my React app with Routing to work on GitHub ...
February 11, 2021 - You just need to add it to your gh-pages branch and display whatever message you want and a link back to your URL. One more note on the routing. When you are using HashRoute you don’t need to change the REACT_APP_FOR_PATH to change between building locally and building for GitHub pages.
🌐
ITNEXT
itnext.io › so-you-want-to-host-your-single-age-react-app-on-github-pages-a826ab01e48
So you want to host your Single Page React App on GitHub Pages? | by Brendan McIlhenny | ITNEXT
April 28, 2018 - With some slight configuration and a few hours staring at various forums and docs I finally got my routes working and rendering the correct components, although for some reason when I manually navigated to certain URLS like “https://bmcilhenny.github.io/trivia-front-end/edit” I stumbled into a 404 error. I could reach this route via my Nav bar on my home page but after I refreshed GitHub was still spewing out a 404 error.