Skip to content

Commit d9cf933

Browse files
fix(router-core): hydrate before initial client route match (#7416)
1 parent 4e42422 commit d9cf933

3 files changed

Lines changed: 77 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/router-core': patch
3+
---
4+
5+
Run custom router hydration before the initial client route match so hydrated router configuration, such as request-specific URL rewrites, can be installed before SSR hydration compares matches.

‎packages/router-core/src/ssr/ssr-client.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@ export async function hydrate(router: AnyRouter): Promise<any> {
9494
nonce,
9595
}
9696

97+
// Allow the user to handle custom hydration data before matching routes.
98+
// This lets hydration install router config that affects matching, e.g. rewrites.
99+
await router.options.hydrate?.(dehydratedData)
100+
97101
// Hydrate the router state
98102
const matches = router.matchRoutes(router.stores.location.get())
99103

@@ -164,9 +168,6 @@ export async function hydrate(router: AnyRouter): Promise<any> {
164168

165169
router.stores.setMatches(matches)
166170

167-
// Allow the user to handle custom hydration data
168-
await router.options.hydrate?.(dehydratedData)
169-
170171
// now that all necessary data is hydrated:
171172
// 1) fully reconstruct the route context
172173
// 2) execute `head()` and `scripts()` for each match

‎packages/router-core/tests/hydrate.test.ts‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { BaseRootRoute, BaseRoute, notFound } from '../src'
44
import { hydrate } from '../src/ssr/client'
55
import { createTestRouter } from './routerTestUtils'
66
import { dehydrateSsrMatchId } from '../src/ssr/ssr-match-id'
7+
import type { LocationRewrite } from '../src'
78
import type { TsrSsrGlobal } from '../src/ssr/types'
89
import type { AnyRouteMatch } from '../src'
910

@@ -395,6 +396,73 @@ describe('hydrate', () => {
395396
expect((mockRouter.state.matches[0] as AnyRouteMatch).id).toBe('/')
396397
})
397398

399+
it('should run custom hydration before matching routes', async () => {
400+
const history = createMemoryHistory({ initialEntries: ['/public'] })
401+
402+
const rootRoute = new BaseRootRoute({})
403+
const internalRoute = new BaseRoute({
404+
getParentRoute: () => rootRoute,
405+
path: '/internal',
406+
component: () => 'Internal',
407+
})
408+
409+
const rewrite: LocationRewrite = {
410+
input: ({ url }) => {
411+
if (url.pathname === '/public') {
412+
url.pathname = '/internal'
413+
}
414+
return url
415+
},
416+
}
417+
418+
mockRouter = createTestRouter({
419+
routeTree: rootRoute.addChildren([internalRoute]),
420+
history,
421+
isServer: true,
422+
hydrate: (dehydrated: { rewrite?: boolean }) => {
423+
if (dehydrated.rewrite) {
424+
mockRouter.update({ rewrite })
425+
}
426+
},
427+
})
428+
429+
mockWindow.$_TSR = {
430+
router: {
431+
manifest: { routes: {} },
432+
dehydratedData: { rewrite: true },
433+
lastMatchId: '/internal/internal',
434+
matches: [
435+
{
436+
i: '__root__/',
437+
s: 'success',
438+
ssr: true,
439+
u: Date.now(),
440+
},
441+
{
442+
i: '/internal/internal',
443+
s: 'success',
444+
ssr: true,
445+
u: Date.now(),
446+
},
447+
],
448+
},
449+
h: vi.fn(),
450+
e: vi.fn(),
451+
c: vi.fn(),
452+
p: vi.fn(),
453+
buffer: [],
454+
initialized: false,
455+
}
456+
457+
await hydrate(mockRouter)
458+
459+
expect(mockRouter.state.location.pathname).toBe('/internal')
460+
expect(mockRouter.state.location.publicHref).toBe('/public')
461+
expect(
462+
mockRouter.state.matches.map((match: AnyRouteMatch) => match.routeId),
463+
).toEqual(['__root__', '/internal'])
464+
})
465+
398466
it('should handle errors during route context hydration', async () => {
399467
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
400468
mockHead.mockImplementation(() => {

0 commit comments

Comments
 (0)