using Tanstack router with a SPA in github pages

630 Views Asked by At

I'm using react + tanstack router + github pages.

this is the page,

https://jbetoreyes.github.io/beyond-brand-boosters

when I go to the about us page with the navigation, the page loads fine, but if I go directly

https://jbetoreyes.github.io/beyond-brand-boosters/about-us

I get a 404.

In react-router there is the Hash Router, I looked in the docs but I haven't find

this is how my code looks like

https://github.com/JBetoReyes/beyond-brand-boosters/blob/master/src/Router.ts

1

There are 1 best solutions below

0
adsy On

Yes, you need to use hash-based routing which is documented here.

The default "browser" routing will exhibit the behaviour you describe in the context of hosting it on Github Pages because Github can only serve static files and is not capable of resolving arbitrary paths back to your index.html.

With hash routing the path part of the URL is always consistent and the hash part is instead used for the location within the react app.

Change:

import { Router, Route, RootRoute } from '@tanstack/react-router';

// Existing code...

export const router = new Router({ routeTree })

To

import { Router, Route, RootRoute, createMemoryHistory } from '@tanstack/react-router';

// Existing code...

const memoryHistory = createMemoryHistory({
  initialEntries: ['/'],
})

export const router = new Router({ routeTree, history: memoryHistory })