GithubHelp home page GithubHelp logo

pjnalls / pages-404-fix Goto Github PK

View Code? Open in Web Editor NEW
1.0 1.0 0.0 172 KB

⚡️🐞🧑‍🏫 Resolve a common GitHub Pages 404 error page

Home Page: https://problemesolvers.github.io/about/

License: MIT License

404 gh-pages react spa static-site

pages-404-fix's Introduction

GitHub Pages 404 Error Page Fix

⚡️🐞🧑‍🏫 How to resolve a common 404 error when deploying a SPA (single-page application) as static content to GitHub Pages

Problem Description

After a SPA with client-side routing is deployed to Pages successfully, the app will return a 404-error page under the following conditions:

1️⃣ if the user refreshes the page on a non-root route
2️⃣ if the user navigates via the browser's address bar to a non-root route

Page not found - GitHub Pages screenshot

Solution Description

Create a 404.html and add it to your public folder.
404.html should redirect to the root of your SPA (index.html) with a param of the current route name (e.g., "currentRoute") the user requested.
Once the SPA returns to the root of the app once again, it can parse the URL to get the current route and navigate to it with the client-side router.

router Solution Steps

Step 1️⃣, add ~/public/404.html and following code to it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- ... -->
    <base href="/" />
  </head>
  <body>
    <div id="root"></div>
    <script src="/redirect.js"></script>
  </body>
</html>

Step 2️⃣, add ~/public/redirect.js and following code to it:

(function () {
  window.location.href = `/${
    window.location.pathname
      ? `?currentRoute=${window.location.pathname.slice(1)}`
      : ""
  }`;
})();

Step 3️⃣, add line after app is instantiated (e.g., ~/src/main.jsx):

/** ... **/
ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

+router.navigate(window.location.href.split("?")[1]?.split("=")[1]);

Done.

router Solution References

(1️⃣) 🏠 Go to https://problemesolvers.github.io/about for a live example of the solution.

(2️⃣) 🧮 Go to https://github.com/problemesolvers/problemesolvers.github.io for the example code of the solution.

(3️⃣) 🚏 See ~/src/router.jsx below for basic React Router reference:

import { createBrowserRouter } from "react-router-dom";
import App from "./App/App";
import Home from "./Home";
import About from "./About";

export const router = createBrowserRouter([
  {
    path: "/",
    element: <App />,
    children: [
      {
        path: "/",
        element: <Home />,
      },
      {
        path: "/about",
        element: <About />,
      },
    ],
  },
]);

(4️⃣) 🌐 See ~/src/main.jsx below for basic web app instantiation reference:

import React from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider } from "react-router-dom";
import { router } from "./router";
import "./index.css";

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <RouterProvider router={router} />
  </React.StrictMode>
);

router.navigate(window.location.href.split("?")[1]?.split("=")[1]);



There's another pattern to the solution that has the same effect documented below:

Routes Solution Steps

Step 1️⃣, add ~/public/404.html and following code to it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- ... -->
    <base href="/" />
  </head>
  <body>
    <div id="root"></div>
    <script src="/redirect.js"></script>
  </body>
</html>

Step 2️⃣, add ~/public/redirect.js and following code to it:

(function () {
  window.location.href = `/${
    window.location.pathname
      ? `?currentRoute=${window.location.pathname.slice(1)}`
      : ""
  }`;
})();

**Step 3️⃣, ensure Routes have been added correctly in App:

<AppShell.Main>
  <Center>
    <Routes location={location} key={location.pathname}>
      <Route
        path="/"
        element={
          <Navigate
            to={`/${
              window.location.href.split("?")[1]?.split("=")[1] ?? "home"
            }`}
            replace
          />
        }
      />
      <Route path="/home" element={<Home />} />
      <Route path="/about" element={<About />} />
      <Route path="/contact" element={<Contact />} />
      <Route path="/*" element={<PageNotFound />} />
    </Routes>
  </Center>
</AppShell.Main>

Done.

Routes Solution References

(1️⃣) 🏠 Go to https://pjnalls.github.io/about for a live example of the solution.

(2️⃣) 🧮 Go to https://github.com/pjnalls/pjnalls.github.io for the example code of the solution.

(4️⃣) 🌐 See ~/src/main.tsx below for basic web app instantiation reference:

import React from "react";
import ReactDOM from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { MantineProvider } from "@mantine/core";
import "@mantine/core/styles.css";

import App from "./pages/App";
import "./styles/index.scss";

ReactDOM.createRoot(document.getElementById("root")!).render(
  <React.StrictMode>
    <MantineProvider defaultColorScheme={"auto"}>
      <BrowserRouter>
        <App />
      </BrowserRouter>
    </MantineProvider>
  </React.StrictMode>
);

pages-404-fix's People

Contributors

pjnalls avatar

Stargazers

Zach Stone avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.