GitHub Pages 08 ๐ Single Page Applications (SPAs) โ Configuring base paths, hash routing, and 404.html fallback redirects for Vite and React
GitHub Pages is fundamentally a static file server, designed to serve fixed assets like HTML, CSS, and images. Single Page Applications (SPAs) built with frameworks like React, Vue, or Angular pose a unique challenge because they utilize client-side routing. In a typical SPA, the browser loads a single index.html file, and the JavaScript router takes over, changing the URL and the view without a full page reload.
However, when a user refreshes a page or visits a deep link directly (e.g., username.github.io/my-repo/dashboard), GitHub Pages looks for a physical directory or file at that path. Since that directory doesn’t exist on the server, the user receives a 404 error. To host an SPA successfully, developers must handle two critical aspects: the project’s base URL and the routing fallback mechanism.
This chapter covers the configuration of the base path for projects not hosted at the root domain, the pros and cons of using Hash Routing, and the “404 redirection hack” that allows standard Browser Routing to function on a static host. We will specifically focus on Vite and React Router implementations.
Key point: SPAs on GitHub Pages fail on direct link access because the server lacks physical files for client-side routes; this is solved by configuring the base path for asset loading and implementing either Hash Routing or a 404.html fallback redirect.
1. The Stateful Client vs. Stateless Server problem.
GitHub Pages has no logic to “rewrite” requests to a single entry point. In a traditional server (like Nginx), you would configure all requests to point to index.html. On GitHub Pages, every request must map to a real file. If you are at /dashboard, the server looks for /dashboard/index.html, which doesn’t exist in an SPA.
2. The Sub-path/Basename problem.
Most GitHub Pages sites are hosted at username.github.io/repo-name/. Without a base configuration, the browser tries to load assets from the root (e.g., /assets/index.js), which fails because the assets actually live at /repo-name/assets/index.js.
3. The Relative Asset problem.
Static site generators often produce relative links. When an SPA is several routes deep (e.g., /user/settings/profile), relative paths for CSS and JS files can break because the browser calculates them relative to the current URL path rather than the project root.
4. The Refresh/Direct Access problem.
While navigating inside an SPA works perfectly (because JavaScript intercepts the click), refreshing the page or sharing a link forces the browser to request the path from GitHub’s servers. Since GitHub doesn’t know about your React routes, it serves a standard 404 page.
5. The Routing Mode trade-off.
Developers must choose between “Hash Routing” (which uses the # symbol to keep everything on one page) and “Browser Routing” (which uses clean URLs). Hash routing is easier for static hosts but aesthetically less pleasing and slightly worse for SEO.
a. Configuring the base Path in Vite
Vite is the modern standard for React/Vue builds. By default, it assumes your site is at the root. For a project-based GitHub Pages site, you must set the base property in vite.config.js. This ensures that all <script> and <link> tags generated in the final HTML file include the repository name.
// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: '/my-repository-name/', // Must match your repo name exactly
})
Once this is set, your production build will correctly reference files. However, you must also inform your router (like React Router) about this base path. In React Router, this is done via the basename prop.
// App.jsx
import { BrowserRouter } from 'react-router-dom';
function App() {
return (
<BrowserRouter basename="/my-repository-name">
{/* Routes go here */}
</BrowserRouter>
);
}
By keeping these two values in sync, you ensure that your application knows where it “lives” both in terms of loading files and determining the active route.
b. Hash Routing: The Simple Solution
Hash Routing is the path of least resistance for hosting SPAs on static servers. Instead of standard paths, it uses the URL fragment (the part after the #). Since everything after the # is never sent to the server, GitHub Pages only ever sees the request for index.html.
import { HashRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<HashRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</HashRouter>
);
}
In this mode, a link to the “About” page looks like https://user.github.io/repo/#/about. When the user refreshes, the browser requests the base URL (which exists), and then the React code loads and reads the #/about fragment to show the correct component. This requires zero server-side configuration and completely avoids 404 errors.
c. The 404.html Fallback Redirect
If you require clean URLs without hashes (e.g., .../about instead of .../#/about), you must use the “404 hack.” This involves creating a 404.html file in your public folder. When GitHub Pages can’t find a route, it serves this 404.html file. We can include a script in that file to capture the current URL and redirect the browser back to index.html with the path data embedded in a query string.
<!-- public/404.html -->
<script type="text/javascript">
var pathSegs = window.location.pathname.split('/');
// Logic to redirect to index.html with the path stored in sessionStorage
// or as a query parameter
window.location.replace(
window.location.protocol + '//' + window.location.hostname +
(window.location.port ? ':' + window.location.port : '') +
pathSegs.slice(0, 2).join('/') + '/?p=' + pathSegs.slice(2).join('/')
);
</script>
Then, in your main index.html, you add a script to check if a redirect just happened. If it did, it uses window.history.replaceState to clean up the URL before the React Router initializes.
// Inside index.html or at the very top of your main entry file
(function() {
var redirect = window.location.search.match(/[?&]p=([^&]*)/);
if (redirect && redirect[1]) {
var newPath = '/' + redirect[1];
window.history.replaceState(null, null, window.location.pathname.slice(0, -1) + newPath);
}
})();
This sequence tricks the browser and the user into seeing a clean URL while the server-side redirection is handled through a temporary 404 state.
Complete Example Session
// ============================================
// PART 1: VITE CONFIGURATION (vite.config.ts)
// ============================================
export default defineConfig({
base: '/portfolio-site/', // Crucial for repo-based pages
build: { outDir: 'dist' }
});
// ============================================
// PART 2: REACT ROUTER SETUP (App.tsx)
// ============================================
import { BrowserRouter, Routes, Route } from 'react-router-dom';
export function App() {
return (
<BrowserRouter basename="/portfolio-site">
<Routes>
<Route path="/" element={<Layout />}>
<Route index element={<Home />} />
<Route path="projects" element={<Projects />} />
</Route>
</Routes>
</BrowserRouter>
);
}
// ============================================
// PART 3: THE 404 REDIRECTOR (public/404.html)
// ============================================
/*
<script>
sessionStorage.redirect = location.href;
location.replace('/portfolio-site/');
</script>
*/
// ============================================
// PART 4: THE REDIRECT HANDLER (public/index.html)
// ============================================
/*
<script>
(function(){
var redirect = sessionStorage.redirect;
delete sessionStorage.redirect;
if (redirect && redirect != location.href) {
history.replaceState(null, null, redirect);
}
})();
</script>
*/
// ============================================
// PART 5: ASSET REFERENCES
// ============================================
// Correct: <img src={`${import.meta.env.BASE_URL}logo.png`} />
// Incorrect: <img src="/logo.png" />
// ============================================
// PART 6: GITHUB ACTIONS PERMISSIONS
// ============================================
// permissions: { pages: write, id-token: write }
// ============================================
// PART 7: HASH ROUTER ALTERNATIVE
// ============================================
// import { HashRouter } from 'react-router-dom';
// <HashRouter> ... </HashRouter> // No 404 hack needed
// ============================================
// PART 8: CUSTOM DOMAIN CHECK
// ============================================
// If using custom domain, base becomes '/'
// ============================================
// PART 9: LINK COMPONENT
// ============================================
// <Link to="/projects">Work</Link> // Works automatically with basename
// ============================================
// PART 10: DEPLOYMENT VERIFICATION
// ============================================
// Check that manifest.json and assets are loaded from /portfolio-site/
The parts covered the configuration of Vite, the setup of React Router with basename, the logic for the 404.html redirect, and how to handle assets properly.
Quick Reference
Configuration Properties
| Tool | Property | Purpose |
|---|---|---|
| Vite | base | Controls asset injection in HTML |
| React Router | basename | Prefixes all internal links |
| Vue Router | base | Same as React Router |
| GitHub Pages | Repo Name | Becomes the base path segment |
Routing Strategies
| Strategy | URL Style | Ease of Setup | 404 Risk |
|---|---|---|---|
| Hash | .../#/path | Very Easy | None |
| Browser | .../path | Moderate | High (Needs Hack) |
| Custom 404 | .../path | Advanced | Low (Handled) |
Path Calculation
| Scenario | Path Example | Base Setting |
|---|---|---|
| Root Site | user.github.io | / |
| Repo Site | user.github.io/repo | /repo/ |
| Custom Domain | example.com | / |
Best Practices
โ Do This:
// Use the BASE_URL env variable for images
<img src={`${import.meta.env.BASE_URL}hero.jpg`} /> // โ
// Set basename in your Router
<BrowserRouter basename="/my-app"> // โ
// Use HashRouter if you want to avoid 404 hacks
<HashRouter> // โ
// Keep the leading and trailing slashes in Vite base
base: '/my-repo/' // โ
โ Don’t Do This:
// Don't hardcode root-relative paths
<img src="/logo.png" /> // โ
// Don't forget basename even if Vite base is set
<BrowserRouter> // โ
// Don't use absolute URLs for internal links
<a href="https://user.github.io/repo/about"> // โ
// Don't put the 404.html in the src folder
// (It must stay in public/dist) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Blank Screen | base is not set in Vite | Add base: '/repo/' to config |
| 404 on Refresh | Using Browser Router without 404 hack | Switch to HashRouter or add 404.html |
| Assets not found | Leading slash missing in base | Ensure /repo/ format |
| Links go to root | basename missing in Router | Add basename to <BrowserRouter> |
| Local dev breaks | base set but not conditional | Use process.env.NODE_ENV check |
Real-World Examples
1. Conditional Vite Base
base: process.env.NODE_ENV === 'production' ? '/repo/' : '/',
2. React Router with Base
<BrowserRouter basename="/portfolio">
3. Image with Public Path
const icon = `${import.meta.env.BASE_URL}assets/icon.svg`;
4. Simple 404 Redirect
<script>location.href = '/repo/index.html';</script>
5. Absolute Asset in CSS
background: url('/repo/bg.png'); /* Avoid if possible */
6. Dynamic Base URL Detection
const base = window.location.pathname.split('/')[1];
7. Vue Router Base
const router = createRouter({ base: '/my-app/', ... });
8. Hash Link
<a href="#/contact">Contact</a>
9. Script in index.html for 404
if (location.search.includes('redirect')) { /* fix history */ }
10. Manifest.json Base
"start_url": "/my-repository-name/",
Visual
Standard Request (No SPA)
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโ
โ Browser โโโ/aboutโโโบโ GitHub Server โโโFoundโโโบโ about.htmlโ
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโ
SPA Request (Failure)
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโ
โ Browser โโโ/aboutโโโบโ GitHub Server โโMissingโโบโ 404 Page โ
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโ
(Server doesn't know /about is a client-side route)
Hash Routing (Success)
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโ
โ Browser โโโ/#/aboutโโบโ GitHub Server โโโFoundโโโบโ index.htmlโ
โโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโ
(Server ignores the # fragment, loads index.html, JS handles rest)
404 Hack Flow
1. Request /about
2. GitHub serves 404.html
3. 404.html script: "Save '/about' to session, go to /index.html"
4. index.html script: "Found '/about' in session, update URL state"
5. React loads at /about
Summary
| Item | Value |
|---|---|
| Vite Config | base: '/repo/' |
| React Router | basename="/repo" |
| Asset Logic | Prefix with BASE_URL |
| Routing (Simple) | HashRouter |
| Routing (Clean) | BrowserRouter + 404.html |
| Entry Point | index.html |
| Sub-path | Required for repo-sites |
Key takeaways:
- The
basepath is mandatory for repos. If your site isn’t at the root of a domain, you must tell Vite and your Router exactly what the sub-folder name is. - Refresh breaks Browser Routing. Static hosts like GitHub Pages cannot resolve non-physical paths. You must use a workaround for direct link access.
- Hash Routing is the robust default. If you don’t mind the
/#/in your URL, it is the most compatible way to host any SPA on a static server. - Redirection requires
404.html. By capturing 404 errors and redirecting them back toindex.html, you can simulate the behavior of a professional web server. - Relative assets are fragile. Always use absolute paths or environment-aware path helpers when referencing images or external scripts in your code.
- Custom domains simplify things. If you use a custom domain (e.g.,
www.mysite.com), you can usually set your base to/and ignore most sub-path headaches.
Remember: Developing an SPA locally works because the dev server (Vite/Webpack) is configured to automatically redirect all 404s to index.html. GitHub Pages does not do this. You must proactively manage the project base and either accept Hash Routing or implement the manual redirection script.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!