Open History to see the last commit
1import { createRouter, RouterHistory } from "@tanstack/react-router";
2
3import { preloadRouteSpeculatively } from "./lib/chunkReloadGuard";
4import { routeTree } from "./routeTree.gen";
5
6export function getRouter(history: RouterHistory) {
7 const router = createRouter({
8 routeTree,
9 history,
10 context: {},
11 defaultPreload: "intent",
12 });
13 // Failed intent preloads reload only when navigation renders the route.
14 const preloadRoute = router.preloadRoute;
15 router.preloadRoute = ((options: Parameters<typeof preloadRoute>[0]) =>
16 preloadRouteSpeculatively(() => preloadRoute(options))) as typeof preloadRoute;
17 return router;
18}
19
20export type AppRouter = ReturnType<typeof getRouter>;
21
22// Overlap route chunks with auth; defer one task so boot requests start first.
23export function preloadInitialRouteChunks(router: AppRouter) {
24 const { pathname } = router.latestLocation;
25 const routes = [...router.getMatchedRoutes(pathname).matchedRoutes];
26 const draftRoute = router.looseRoutesById["/_chat/draft/$draftId"];
27 if (pathname === "/" && draftRoute) routes.push(draftRoute);
28 setTimeout(() => {
29 for (const route of routes) {
30 // Failures surface again when the router loads the same chunk.
31 void Promise.resolve(router.loadRouteChunk(route)).catch(() => undefined);
32 }
33 }, 0);
34}
35
36declare module "@tanstack/react-router" {
37 interface Register {
38 router: AppRouter;
39 }
40}