I set up routers for the home page ("/") and the about page("/about") in my react app. After Deploying to Github Pages, I encountered a 404 error when trying to navigate to the about page
Cause:
Github Pages only support static file hosting and it cannot handle dynamic routing, so the URL routes cannot be processed correctly
Solution:
Use HashRouter instead of BrowserRouter, which stores routing infomation after the '#' symbol in the URL, which is not sent to the server. This allows the frontend routing to work normally.
import React from 'react';
import { HashRouter, Route, Routes } from 'react-router-dom';
import Home from './components/Home';
import About from './components/About';
function App() {
return (
<HashRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</HashRouter>
);
}
export default App;
By solving this issue, i gained a better understanding of the following concepts:
Static Hosting: Github Pages is a static hosting service and cannot handle server-side routing
Front-End/Back-End Separations: Github Pages is great to host the front-end, and I can use other platform, such as AWS, to deploy the back-end API, allowing for a scalable and modular application architecure
Problem:
I set up routers for the home page ("/") and the about page("/about") in my react app. After Deploying to Github Pages, I encountered a 404 error when trying to navigate to the about page
Cause:
Github Pages only support static file hosting and it cannot handle dynamic routing, so the URL routes cannot be processed correctly
Solution:
Use
HashRouter
instead ofBrowserRouter
, which stores routing infomation after the '#' symbol in the URL, which is not sent to the server. This allows the frontend routing to work normally.