+ )
+ })}
+ >
)
},
})
@@ -65,38 +142,279 @@ const Root = Vue.defineComponent({
setup() {
return () => (
<>
- {selectors.map((selector) => (
-
+ {rootSelectors.map((selector) => (
+
))}
- {selectors.map((selector) => (
-
- ))}
- {selectors.map((selector) => (
-
+ {rootSelectors.map((selector) => (
+
))}
+
>
)
},
})
-const root = createRootRoute({
+const rootRoute = createRootRoute({
component: Root,
})
-const route = createRoute({
- getParentRoute: () => root,
- path: '/$id',
- component: () => ,
+const ItemParamsSubscriber = Vue.defineComponent({
+ setup() {
+ const params = itemsRoute.useParams({
+ select: (params) => runPerfSelectorComputation(params.id),
+ })
+
+ return () => {
+ void runPerfSelectorComputation(params.value)
+ return null
+ }
+ },
+})
+
+const SearchStateSubscriber = Vue.defineComponent({
+ setup() {
+ const search = searchRoute.useSearch({
+ select: (search) =>
+ runPerfSelectorComputation(search.page + search.filter.length),
+ })
+
+ return () => {
+ void runPerfSelectorComputation(search.value)
+ return null
+ }
+ },
+})
+
+const SearchLoaderDepsSubscriber = Vue.defineComponent({
+ setup() {
+ const loaderDeps = searchRoute.useLoaderDeps({
+ select: (loaderDeps) =>
+ runPerfSelectorComputation(loaderDeps.page + loaderDeps.filter.length),
+ })
+
+ return () => {
+ void runPerfSelectorComputation(loaderDeps.value)
+ return null
+ }
+ },
+})
+
+const SearchLoaderDataSubscriber = Vue.defineComponent({
+ setup() {
+ const loaderData = searchRoute.useLoaderData({
+ select: (loaderData) =>
+ runPerfSelectorComputation(loaderData.seed + loaderData.checksum),
+ })
+
+ return () => {
+ void runPerfSelectorComputation(loaderData.value)
+ return null
+ }
+ },
+})
+
+const ContextParamsSubscriber = Vue.defineComponent({
+ setup() {
+ const params = contextRoute.useParams({
+ select: (params) => runPerfSelectorComputation(Number(params.id)),
+ })
+
+ return () => {
+ void runPerfSelectorComputation(params.value)
+ return null
+ }
+ },
+})
+
+const ContextRouteSubscriber = Vue.defineComponent({
+ setup() {
+ const context = contextRoute.useRouteContext({
+ select: (context) => runPerfSelectorComputation(context.sectionSeed),
+ })
+
+ return () => {
+ void runPerfSelectorComputation(context.value)
+ return null
+ }
+ },
+})
+
+const ItemsPage = Vue.defineComponent({
+ setup() {
+ return () => (
+ <>
+ {routeSelectors.map((selector) => (
+
+ ))}
+
+ Details
+
+
+ Preserve search on item
+
+
+ >
+ )
+ },
+})
+
+const ItemDetailsPage = Vue.defineComponent({
+ setup() {
+ return () => (
+ <>
+ {routeSelectors.map((selector) => (
+
+ ))}
+
+ Back to item
+
+ >
+ )
+ },
+})
+
+const SearchPage = Vue.defineComponent({
+ setup() {
+ return () => (
+ <>
+ {routeSelectors.map((selector) => (
+
+ ))}
+ {routeSelectors.map((selector) => (
+
+ ))}
+ {routeSelectors.map((selector) => (
+
+ ))}
+ ({
+ page: prev.page + 1,
+ filter: prev.filter,
+ junk: 'local-updater',
+ })}
+ activeOptions={{ includeSearch: true }}
+ activeProps={{ class: 'active-link' }}
+ inactiveProps={{ class: 'inactive-link' }}
+ >
+ Next page
+
+ >
+ )
+ },
+})
+
+const ContextPage = Vue.defineComponent({
+ setup() {
+ return () => (
+ <>
+ {routeSelectors.map((selector) => (
+
+ ))}
+ {routeSelectors.map((selector) => (
+
+ ))}
+ >
+ )
+ },
+})
+
+const itemsRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: '/items/$id',
+ params: {
+ parse: (params) => ({
+ ...params,
+ id: normalizePage(params.id),
+ }),
+ stringify: (params) => ({
+ ...params,
+ id: `${params.id}`,
+ }),
+ },
+ onEnter: noop,
+ onStay: noop,
+ onLeave: noop,
+ component: ItemsPage,
+})
+
+const itemDetailsRoute = createRoute({
+ getParentRoute: () => itemsRoute,
+ path: 'details',
+ component: ItemDetailsPage,
+})
+
+const searchRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: '/search',
+ validateSearch: (search: Record) => ({
+ page: normalizePage(search.page),
+ filter: normalizeFilter(search.filter),
+ }),
+ search: {
+ middlewares: [
+ ({ search, next }) => {
+ const result = next(search)
+ return {
+ page: result.page,
+ filter: result.filter,
+ }
+ },
+ ],
+ },
+ loaderDeps: ({ search }) => ({
+ page: search.page,
+ filter: search.filter,
+ }),
+ loader: ({ deps }) => ({
+ seed: deps.page * 31 + deps.filter.length,
+ checksum: deps.page * 17 + deps.filter.length,
+ }),
+ staleTime: 60_000,
+ gcTime: 60_000,
+ component: SearchPage,
+})
+
+const contextRoute = createRoute({
+ getParentRoute: () => rootRoute,
+ path: '/ctx/$id',
+ beforeLoad: ({ params }) => ({
+ sectionSeed: Number(params.id) * 13 + 1,
+ }),
+ component: ContextPage,
})
export function mountTestApp(container: Element) {
const router = createRouter({
history: createMemoryHistory({
- initialEntries: ['/0'],
+ initialEntries: ['/items/0'],
}),
scrollRestoration: true,
- routeTree: root.addChildren([route]),
+ routeTree: rootRoute.addChildren([
+ itemsRoute.addChildren([itemDetailsRoute]),
+ searchRoute,
+ contextRoute,
+ ]),
})
const component =
diff --git a/benchmarks/client-nav/vue/setup.ts b/benchmarks/client-nav/vue/setup.ts
index 5b4a91cb05..a745020302 100644
--- a/benchmarks/client-nav/vue/setup.ts
+++ b/benchmarks/client-nav/vue/setup.ts
@@ -1,5 +1,6 @@
import type { NavigateOptions } from '@tanstack/router-core'
import type * as App from './app'
+import { getRequiredLink, waitForRequiredLink } from '../setup-helpers'
const appModulePath = './dist/app.js'
const { mountTestApp } = (await import(appModulePath)) as typeof App
@@ -11,19 +12,20 @@ export function setup() {
)
}
- let id = 0
- let unmount: (() => void) | undefined = undefined
let container: HTMLDivElement | undefined = undefined
+ let unmount: (() => void) | undefined = undefined
let unsub = () => {}
+ let stepIndex = 0
let next: () => Promise = () => Promise.reject('Test not initialized')
async function before() {
- id = 0
+ stepIndex = 0
container = document.createElement('div')
document.body.append(container)
const { router, unmount: dispose } = mountTestApp(container)
unmount = dispose
+
let resolveRendered: () => void = () => {}
unsub = router.subscribe('onRendered', () => {
resolveRendered()
@@ -35,18 +37,59 @@ export function setup() {
router.navigate(opts)
})
- next = () => {
- const nextId = id++
+ const click = (testId: string, cache?: Map) =>
+ new Promise((resolveNext) => {
+ resolveRendered = resolveNext
- return navigate({
- to: '/$id',
- params: { id: nextId },
- // update search every 2 navigations, to still test them, but also measure the impact of granular re-rendering
- search: { id: Math.floor(nextId / 2) },
- replace: true,
+ getRequiredLink(container!, testId, cache).dispatchEvent(
+ new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ button: 0,
+ }),
+ )
})
- }
+
await router.load()
+
+ const cachedLinks = new Map()
+ for (const testId of ['go-items-1', 'go-items-2', 'go-search', 'go-ctx']) {
+ await waitForRequiredLink(container, testId, cachedLinks)
+ }
+
+ const steps = [
+ () => click('go-items-1', cachedLinks),
+ () => click('items-details'),
+ () =>
+ navigate({
+ to: '/items/$id/details',
+ params: { id: 2 },
+ replace: true,
+ }),
+ () => click('items-parent'),
+ () => click('go-search', cachedLinks),
+ () => click('search-next-page'),
+ () =>
+ navigate({
+ to: '/search',
+ search: { page: 1, filter: 'all' },
+ replace: true,
+ }),
+ () => click('go-ctx', cachedLinks),
+ () =>
+ navigate({
+ to: '/ctx/$id',
+ params: { id: 2 },
+ replace: true,
+ }),
+ () => click('go-items-2', cachedLinks),
+ ] as const
+
+ next = () => {
+ const step = steps[stepIndex % steps.length]!
+ stepIndex += 1
+ return step()
+ }
}
function after() {
diff --git a/benchmarks/ssr/package.json b/benchmarks/ssr/package.json
index 19911317ee..c1c15a1a27 100644
--- a/benchmarks/ssr/package.json
+++ b/benchmarks/ssr/package.json
@@ -24,16 +24,17 @@
"@tanstack/vue-start": "workspace:^",
"react": "^19.0.0",
"react-dom": "^19.0.0",
- "solid-js": "^1.9.10",
+ "solid-js": "2.0.0-beta.5",
+ "@solidjs/web": "2.0.0-beta.5",
"vue": "^3.5.16"
},
"devDependencies": {
"@codspeed/vitest-plugin": "^5.0.1",
- "@vitejs/plugin-react": "^4.3.4",
- "@vitejs/plugin-vue-jsx": "^4.1.2",
- "typescript": "^5.7.2",
- "vite": "^7.3.1",
- "vite-plugin-solid": "^2.11.10",
+ "@vitejs/plugin-react": "^6.0.1",
+ "@vitejs/plugin-vue-jsx": "^5.1.5",
+ "typescript": "^6.0.2",
+ "vite": "^8.0.0",
+ "vite-plugin-solid": "3.0.0-next.4",
"vitest": "^4.0.17"
},
"nx": {
diff --git a/benchmarks/ssr/solid/src/workload.tsx b/benchmarks/ssr/solid/src/workload.tsx
index 76fcae555a..eb65591ad5 100644
--- a/benchmarks/ssr/solid/src/workload.tsx
+++ b/benchmarks/ssr/solid/src/workload.tsx
@@ -29,9 +29,10 @@ function ParamsProbe(props: { salt: number }) {
),
})
- createEffect(() => {
- void params()
- })
+ createEffect(
+ () => params(),
+ () => {},
+ )
return null
}
@@ -43,9 +44,10 @@ function SearchProbe(props: { salt: number }) {
runSelectorWork(String(nextSearch.q ?? ''), props.salt),
})
- createEffect(() => {
- void search()
- })
+ createEffect(
+ () => search(),
+ () => {},
+ )
return null
}
@@ -73,9 +75,9 @@ function LinkProbe(props: { salt: number }) {
export function RouteWorkload() {
return (
<>
- {(probe) => }
- {(probe) => }
- {(probe) => }
+ {(probe) => }
+ {(probe) => }
+ {(probe) => }
>
)
}
diff --git a/docs/router/api/router/RouterEventsType.md b/docs/router/api/router/RouterEventsType.md
index 45d6431cdf..c79bb47f81 100644
--- a/docs/router/api/router/RouterEventsType.md
+++ b/docs/router/api/router/RouterEventsType.md
@@ -13,6 +13,7 @@ type RouterEvents = {
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
+ hashChanged: boolean
}
onBeforeLoad: {
type: 'onBeforeLoad'
@@ -20,6 +21,7 @@ type RouterEvents = {
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
+ hashChanged: boolean
}
onLoad: {
type: 'onLoad'
@@ -27,6 +29,7 @@ type RouterEvents = {
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
+ hashChanged: boolean
}
onResolved: {
type: 'onResolved'
@@ -34,6 +37,7 @@ type RouterEvents = {
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
+ hashChanged: boolean
}
onBeforeRouteMount: {
type: 'onBeforeRouteMount'
@@ -41,6 +45,7 @@ type RouterEvents = {
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
+ hashChanged: boolean
}
onInjectedHtml: {
type: 'onInjectedHtml'
@@ -49,6 +54,9 @@ type RouterEvents = {
type: 'onRendered'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
+ pathChanged: boolean
+ hrefChanged: boolean
+ hashChanged: boolean
}
}
```
@@ -59,7 +67,7 @@ Once an event is emitted, the following properties will be present on the event
### `type` property
-- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved`
+- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered | onInjectedHtml`
- The type of the event
- This is useful for discriminating between events in a listener function.
@@ -83,6 +91,11 @@ Once an event is emitted, the following properties will be present on the event
- Type: `boolean`
- `true` if the href has changed between the `fromLocation` and `toLocation`.
+### `hashChanged` property
+
+- Type: `boolean`
+- `true` if the hash has changed between the `fromLocation` and `toLocation`.
+
## Example
```tsx
diff --git a/docs/router/api/router/RouterStateType.md b/docs/router/api/router/RouterStateType.md
index 6c4d2aca93..a77f4e775f 100644
--- a/docs/router/api/router/RouterStateType.md
+++ b/docs/router/api/router/RouterStateType.md
@@ -11,7 +11,6 @@ type RouterState = {
isLoading: boolean
isTransitioning: boolean
matches: Array
- pendingMatches: Array
location: ParsedLocation
resolvedLocation: ParsedLocation
}
@@ -41,11 +40,6 @@ The `RouterState` type contains all of the properties that are available on the
- Type: [`Array`](./RouteMatchType.md)
- An array of all of the route matches that have been resolved and are currently active.
-### `pendingMatches` property
-
-- Type: [`Array`](./RouteMatchType.md)
-- An array of all of the route matches that are currently pending.
-
### `location` property
- Type: [`ParsedLocation`](./ParsedLocationType.md)
diff --git a/docs/router/api/router/RouterType.md b/docs/router/api/router/RouterType.md
index 0b829b85e0..757a6098ca 100644
--- a/docs/router/api/router/RouterType.md
+++ b/docs/router/api/router/RouterType.md
@@ -23,10 +23,11 @@ An instance of the `Router` has the following properties and methods:
### `.subscribe` method
-- Type: `(eventType: TType, fn: ListenerFn) => (event: RouterEvent) => void`
+- Type: `(eventType: TType, fn: ListenerFn) => () => void`
- Subscribes to a [`RouterEvent`](./RouterEventsType.md).
- Returns a function that can be used to unsubscribe from the event.
-- The callback provided to the returned function will be called with the event that was emitted.
+- The listener will be called with the event payload whenever that event is emitted.
+- See the [Router Events guide](../../guide/router-events.md) for lifecycle ordering and usage patterns.
### `.matchRoutes` method
diff --git a/docs/router/api/router/retainSearchParamsFunction.md b/docs/router/api/router/retainSearchParamsFunction.md
index eeac38bcd7..18600fd346 100644
--- a/docs/router/api/router/retainSearchParamsFunction.md
+++ b/docs/router/api/router/retainSearchParamsFunction.md
@@ -15,14 +15,14 @@ If `true` is passed in, all search params will be retained.
```tsx
import { z } from 'zod'
import { createRootRoute, retainSearchParams } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
const searchSchema = z.object({
rootValue: z.string().optional(),
})
export const Route = createRootRoute({
- validateSearch: zodValidator(searchSchema),
+ // Use the schema directly for Zod v4
+ validateSearch: searchSchema,
search: {
middlewares: [retainSearchParams(['rootValue'])],
},
@@ -32,7 +32,6 @@ export const Route = createRootRoute({
```tsx
import { z } from 'zod'
import { createFileRoute, retainSearchParams } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
const searchSchema = z.object({
one: z.string().optional(),
@@ -40,7 +39,8 @@ const searchSchema = z.object({
})
export const Route = createFileRoute('/')({
- validateSearch: zodValidator(searchSchema),
+ // Use the schema directly for Zod v4
+ validateSearch: searchSchema,
search: {
middlewares: [retainSearchParams(true)],
},
diff --git a/docs/router/api/router/stripSearchParamsFunction.md b/docs/router/api/router/stripSearchParamsFunction.md
index bfbb57a740..08164c39ba 100644
--- a/docs/router/api/router/stripSearchParamsFunction.md
+++ b/docs/router/api/router/stripSearchParamsFunction.md
@@ -18,7 +18,6 @@ title: Search middleware to strip search params
```tsx
import { z } from 'zod'
import { createFileRoute, stripSearchParams } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
const defaultValues = {
one: 'abc',
@@ -31,7 +30,8 @@ const searchSchema = z.object({
})
export const Route = createFileRoute('/')({
- validateSearch: zodValidator(searchSchema),
+ // for Zod v4, use the schema directly
+ validateSearch: searchSchema,
search: {
// strip default values
middlewares: [stripSearchParams(defaultValues)],
@@ -42,7 +42,6 @@ export const Route = createFileRoute('/')({
```tsx
import { z } from 'zod'
import { createRootRoute, stripSearchParams } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
const searchSchema = z.object({
hello: z.string().default('world'),
@@ -50,7 +49,8 @@ const searchSchema = z.object({
})
export const Route = createRootRoute({
- validateSearch: zodValidator(searchSchema),
+ // for Zod v4, use the schema directly
+ validateSearch: searchSchema,
search: {
// always remove `hello`
middlewares: [stripSearchParams(['hello'])],
@@ -61,7 +61,6 @@ export const Route = createRootRoute({
```tsx
import { z } from 'zod'
import { createFileRoute, stripSearchParams } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
const searchSchema = z.object({
one: z.string().default('abc'),
@@ -69,7 +68,8 @@ const searchSchema = z.object({
})
export const Route = createFileRoute('/')({
- validateSearch: zodValidator(searchSchema),
+ // for Zod v4, use the schema directly
+ validateSearch: searchSchema,
search: {
// remove all search params
middlewares: [stripSearchParams(true)],
diff --git a/docs/router/api/router/useBlockerHook.md b/docs/router/api/router/useBlockerHook.md
index 98d4a06c3b..3d9c00d602 100644
--- a/docs/router/api/router/useBlockerHook.md
+++ b/docs/router/api/router/useBlockerHook.md
@@ -20,7 +20,7 @@ The `useBlocker` hook accepts a single _required_ argument, an option object:
- Think of this function as telling the router if it should block the navigation, so returning `true` mean that it should block the navigation and `false` meaning that it should be allowed
```ts
-interface ShouldBlockFnLocation<...> {
+type ShouldBlockFnLocation<...> = {
routeId: TRouteId
fullPath: TFullPath
pathname: string
diff --git a/docs/router/api/router/useChildMatchesHook.md b/docs/router/api/router/useChildMatchesHook.md
index cf31d21016..d6de892192 100644
--- a/docs/router/api/router/useChildMatchesHook.md
+++ b/docs/router/api/router/useChildMatchesHook.md
@@ -6,7 +6,7 @@ title: useChildMatches hook
The `useChildMatches` hook returns all of the child [`RouteMatch`](./RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the `useMatch` hook.**
> [!IMPORTANT]
-> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`.
+> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches.
## useChildMatches options
diff --git a/docs/router/api/router/useParentMatchesHook.md b/docs/router/api/router/useParentMatchesHook.md
index fe4068f397..7afc5585a6 100644
--- a/docs/router/api/router/useParentMatchesHook.md
+++ b/docs/router/api/router/useParentMatchesHook.md
@@ -6,7 +6,7 @@ title: useParentMatches hook
The `useParentMatches` hook returns all of the parent [`RouteMatch`](./RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the `useMatch` hook.**
> [!IMPORTANT]
-> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`.
+> If the router has pending matches and they are showing their pending component fallbacks, pending matches are used instead of active matches.
## useParentMatches options
diff --git a/docs/router/api/router/useRouterStateHook.md b/docs/router/api/router/useRouterStateHook.md
index bcded1d415..24fd8f94b2 100644
--- a/docs/router/api/router/useRouterStateHook.md
+++ b/docs/router/api/router/useRouterStateHook.md
@@ -6,7 +6,7 @@ title: useRouterState hook
The `useRouterState` method is a hook that returns the current internal state of the router. This hook is useful for accessing the current state of the router in a component.
> [!TIP]
-> If you want to access the current location or the current matches, you should try out the [`useLocation`](./useLocationHook.md) and [`useMatches`](./useMatchesHook.md) hooks first. These hooks are designed to be more ergonomic and easier to use than accessing the router state directly.
+> If you want to access the current location or the current matches, you should try out the [`useLocation`](./useLocationHook.md) and [`useMatches`](./useMatchesHook.md) hooks first. These hooks are designed to be more performant, more ergonomic and easier to use than accessing the router state directly.
## useRouterState options
diff --git a/docs/router/config.json b/docs/router/config.json
index e13b8e403f..fd564ceb28 100644
--- a/docs/router/config.json
+++ b/docs/router/config.json
@@ -163,6 +163,10 @@
"label": "Navigation",
"to": "guide/navigation"
},
+ {
+ "label": "Router Events",
+ "to": "guide/router-events"
+ },
{
"label": "Path Params",
"to": "guide/path-params"
diff --git a/docs/router/guide/data-mutations.md b/docs/router/guide/data-mutations.md
index 53899f51d4..7ffb403bfb 100644
--- a/docs/router/guide/data-mutations.md
+++ b/docs/router/guide/data-mutations.md
@@ -123,6 +123,8 @@ function ChatRoom() {
## Using the `router.subscribe` method
+See the [Router Events guide](./router-events.md) for a more complete walkthrough of the available events and when to use them.
+
For libraries that don't have a keying mechanism, we'll likely need to manually reset the mutation state when the user navigates away from the screen. To solve this, we can use TanStack Router's `invalidate` and `subscribe` method to clear mutation states when the user is no longer in need of them.
The `router.subscribe` method is a function that subscribes a callback to various router events. The event in particular that we'll use here is the `onResolved` event. It's important to understand that this event is fired when the location path is _changed (not just reloaded) and has finally resolved_.
diff --git a/docs/router/guide/document-head-management.md b/docs/router/guide/document-head-management.md
index cf66544a4a..381462e20a 100644
--- a/docs/router/guide/document-head-management.md
+++ b/docs/router/guide/document-head-management.md
@@ -68,6 +68,24 @@ The `` component is **required** to render the head, title, meta,
It should be **rendered either in the `` tag of your root layout or as high up in the component tree as possible** if your application doesn't or can't manage the `` tag.
+For manifest-managed assets, you can also set `crossorigin` values on emitted
+`modulepreload` and stylesheet links:
+
+```tsx
+
+
+
+```
+
+`assetCrossOrigin` only applies to manifest-managed asset links emitted by Start.
+If you also set `crossOrigin` via `transformAssets` (either the object shorthand
+or a callback return value), `assetCrossOrigin` wins.
+
### Start/Full-Stack Applications
diff --git a/docs/router/guide/router-events.md b/docs/router/guide/router-events.md
new file mode 100644
index 0000000000..ca798a9676
--- /dev/null
+++ b/docs/router/guide/router-events.md
@@ -0,0 +1,129 @@
+---
+title: Router Events
+---
+
+TanStack Router exposes router lifecycle events through `router.subscribe`. This is useful for imperative side effects like analytics, resetting external state, or running DOM-dependent logic after navigation.
+
+## Basic usage
+
+`router.subscribe` takes an event name and a listener, then returns an unsubscribe function:
+
+```tsx
+const unsubscribe = router.subscribe('onResolved', (event) => {
+ console.info('Navigation finished:', event.toLocation.href)
+})
+
+// Later, clean up the listener
+unsubscribe()
+```
+
+## When to use it
+
+`router.subscribe` is best for imperative integrations that need to observe navigation without driving rendering:
+
+- Analytics and pageview tracking
+- Resetting external caches or mutation state
+- Logging navigation timing and transitions
+- Running DOM-dependent logic after routes render
+
+If you need reactive UI updates, prefer framework hooks like `useRouterState`, `useSearch`, and `useParams` instead of subscribing manually.
+
+## Available events
+
+TanStack Router emits these lifecycle events:
+
+- `onBeforeNavigate` - right before a navigation begins
+- `onBeforeLoad` - before route loading starts
+- `onLoad` - after the next location has committed and route matches have loaded
+- `onBeforeRouteMount` - after loading finishes, just before route components mount
+- `onResolved` - after the navigation has fully resolved
+- `onRendered` - after the route has rendered
+
+For the full event payload types, see the [`RouterEvents` type](../api/router/RouterEventsType.md).
+
+## Typical event flow
+
+For a normal navigation, the events usually flow like this:
+
+1. `onBeforeNavigate`
+2. `onBeforeLoad`
+3. `onLoad`
+4. `onBeforeRouteMount`
+5. `onResolved`
+6. `onRendered`
+
+You usually do not need every event. A good rule of thumb is:
+
+- Use `onBeforeNavigate` or `onBeforeLoad` to observe navigation start
+- Use `onResolved` for analytics and cleanup after navigation finishes
+- Use `onRendered` for DOM-dependent work
+
+## Event payload
+
+Navigation events receive location change metadata describing what changed:
+
+```tsx
+const unsubscribe = router.subscribe('onBeforeNavigate', (event) => {
+ console.info({
+ from: event.fromLocation?.href,
+ to: event.toLocation.href,
+ pathChanged: event.pathChanged,
+ hrefChanged: event.hrefChanged,
+ hashChanged: event.hashChanged,
+ })
+})
+```
+
+A few useful details:
+
+- `fromLocation` can be `undefined` on the initial load
+- `pathChanged` tells you whether the pathname changed
+- `hrefChanged` includes pathname, search, and hash changes
+- `hashChanged` is useful for distinguishing hash-only navigations
+
+## Common patterns
+
+### Track pageviews
+
+`onResolved` is a good default for analytics because it fires after navigation finishes:
+
+```tsx
+const unsubscribe = router.subscribe('onResolved', ({ toLocation }) => {
+ analytics.track('page_view', {
+ path: toLocation.pathname,
+ href: toLocation.href,
+ })
+})
+```
+
+### Clear external mutation state
+
+If you use a mutation library without keyed mutation state, clear it after navigation:
+
+```tsx
+const unsubscribe = router.subscribe('onResolved', ({ pathChanged }) => {
+ if (pathChanged) {
+ mutationCache.clear()
+ }
+})
+```
+
+### Run DOM-dependent logic
+
+Use `onRendered` when your side effect depends on the new route content already being in the DOM:
+
+```tsx
+const unsubscribe = router.subscribe('onRendered', ({ toLocation }) => {
+ focusPageHeading(toLocation.pathname)
+})
+```
+
+## Unsubscribing in components
+
+If you subscribe from a component or framework effect, always return the unsubscribe function from your cleanup so the listener is removed when the component unmounts.
+
+## Related APIs
+
+- [`Router` type](../api/router/RouterType.md)
+- [`RouterEvents` type](../api/router/RouterEventsType.md)
+- [Data Mutations](./data-mutations.md)
diff --git a/docs/router/guide/search-params.md b/docs/router/guide/search-params.md
index 53e9cd1c8a..cbc84c5526 100644
--- a/docs/router/guide/search-params.md
+++ b/docs/router/guide/search-params.md
@@ -196,7 +196,9 @@ For validation libraries we recommend using adapters which infer the correct `in
### Zod
-An adapter is provided for [Zod](https://zod.dev/) which will pipe through the correct `input` type and `output` type
+An adapter is provided for [Zod](https://zod.dev/) which will pipe through the correct `input` type and `output` type.
+
+For Zod v3:
```tsx
import { zodValidator } from '@tanstack/zod-adapter'
@@ -213,13 +215,30 @@ export const Route = createFileRoute('/shop/products/')({
})
```
-The important part here is the following use of `Link` no longer requires `search` params
+With Zod v4, you should directly use the schema in `validateSearch`:
+
+```tsx
+import { z } from 'zod'
+
+const productSearchSchema = z.object({
+ page: z.number().default(1),
+ filter: z.string().default(''),
+ sort: z.enum(['newest', 'oldest', 'price']).default('newest'),
+})
+
+export const Route = createFileRoute('/shop/products/')({
+ // With Zod v4, we can use the schema without the adapter
+ validateSearch: productSearchSchema,
+})
+```
+
+The important part here is the following use of `Link` no longer requires `search` params:
```tsx
```
-However the use of `catch` here overrides the types and makes `page`, `filter` and `sort` `unknown` causing type loss. We have handled this case by providing a `fallback` generic function which retains the types but provides a `fallback` value when validation fails
+In Zod v3, the use of `catch` here overrides the types and makes `page`, `filter` and `sort` `unknown` causing type loss. We have handled this case by providing a `fallback` generic function which retains the types but provides a `fallback` value when validation fails:
```tsx
import { fallback, zodValidator } from '@tanstack/zod-adapter'
@@ -240,7 +259,9 @@ export const Route = createFileRoute('/shop/products/')({
Therefore when navigating to this route, `search` is optional and retains the correct types.
-While not recommended, it is also possible to configure `input` and `output` type in case the `output` type is more accurate than the `input` type
+In Zod v4, schemas may use `catch` instead of the fallback and will retain type inference throughout.
+
+While not recommended, it is also possible to configure `input` and `output` type in case the `output` type is more accurate than the `input` type:
```tsx
const productSearchSchema = z.object({
@@ -457,7 +478,7 @@ Now that you've learned how to read your route's search params, you'll be happy
The best way to update search params is to use the `search` prop on the `` component.
-If the search for the current page shall be updated and the `from` prop is specified, the `to` prop can be omitted.
+If the search for the current page shall be updated and the `from` prop is specified, the `to` prop can be omitted.
Here's an example:
```tsx title="src/routes/shop/products.tsx"
@@ -478,7 +499,7 @@ const ProductList = () => {
If you want to update the search params in a generic component that is rendered on multiple routes, specifying `from` can be challenging.
-In this scenario you can set `to="."` which will give you access to loosely typed search params.
+In this scenario you can set `to="."` which will give you access to loosely typed search params.
Here is an example that illustrates this:
```tsx
diff --git a/docs/router/guide/ssr.md b/docs/router/guide/ssr.md
index 6e3c0a41c9..6cb98766d1 100644
--- a/docs/router/guide/ssr.md
+++ b/docs/router/guide/ssr.md
@@ -234,7 +234,7 @@ hydrateRoot(document, )
# Solid
```tsx title="src/entry-client.tsx"
-import { hydrate } from 'solid-js/web'
+import { hydrate } from '@solidjs/web'
import { RouterClient } from '@tanstack/solid-router/ssr/client'
import { createRouter } from './router'
diff --git a/docs/router/how-to/setup-basic-search-params.md b/docs/router/how-to/setup-basic-search-params.md
index 8c9cbbe2e8..27e49f7584 100644
--- a/docs/router/how-to/setup-basic-search-params.md
+++ b/docs/router/how-to/setup-basic-search-params.md
@@ -10,7 +10,6 @@ Set up search parameters with schema validation (recommended for production):
```tsx
import { createFileRoute } from '@tanstack/react-router'
-import { zodValidator, fallback } from '@tanstack/zod-adapter'
import { z } from 'zod'
const productSearchSchema = z.object({
@@ -20,7 +19,7 @@ const productSearchSchema = z.object({
})
export const Route = createFileRoute('/products')({
- validateSearch: zodValidator(productSearchSchema),
+ validateSearch: productSearchSchema,
component: ProductsPage,
})
@@ -50,7 +49,25 @@ function ProductsPage() {
## Validation Library Setup
-TanStack Router supports any standard schema-compliant validation library. This guide focuses on Zod for examples, but you can use any validation library:
+TanStack Router supports any standard schema-compliant validation library. This guide focuses on Zod for examples, but you can use any validation library.
+
+Using Zod v4:
+
+```tsx
+import { z } from 'zod'
+
+const searchSchema = z.object({
+ page: z.number().default(1),
+ category: z.string().default('all').catch('all'),
+})
+
+export const Route = createFileRoute('/products')({
+ validateSearch: searchSchema,
+ component: ProductsPage,
+})
+```
+
+For Zod v3:
```bash
npm install zod @tanstack/zod-adapter
@@ -75,15 +92,9 @@ export const Route = createFileRoute('/products')({
## Step-by-Step Setup with Zod
-The rest of this guide uses Zod for examples, but the patterns apply to any validation library.
+The rest of this guide uses Zod v4 for examples, but the patterns apply to any validation library.
-### Step 1: Install Dependencies
-
-```bash
-npm install zod @tanstack/zod-adapter
-```
-
-### Step 2: Define Your Search Schema
+### Step 1: Define Your Search Schema
Start by identifying what search parameters your route needs:
@@ -93,40 +104,38 @@ import { fallback } from '@tanstack/zod-adapter'
const shopSearchSchema = z.object({
// Pagination
- page: fallback(z.number(), 1).default(1),
- limit: fallback(z.number(), 20).default(20),
+ page: z.number().default(1),
+ limit: z.number().default(20),
// Filtering
- category: fallback(z.string(), 'all').default('all'),
- minPrice: fallback(z.number(), 0).default(0),
- maxPrice: fallback(z.number(), 1000).default(1000),
+ category: z.string().default('all'),
+ minPrice: z.number().default(0),
+ maxPrice: z.number().default(1000),
// Settings
- sort: fallback(z.enum(['name', 'price', 'date']), 'name').default('name'),
- ascending: fallback(z.boolean(), true).default(true),
+ sort: z.enum(['name', 'price', 'date']).default('name'),
+ ascending: z.boolean().default(true),
// Optional parameters
searchTerm: z.string().optional(),
- showOnlyInStock: fallback(z.boolean(), false).default(false),
+ showOnlyInStock: z.boolean().default(false),
})
type ShopSearch = z.infer
```
-### Step 3: Add Schema Validation to Route
+### Step 2: Add Schema Validation to Route
-Use the validation adapter to connect your schema to the route:
+Connect your schema to the route:
```tsx
-import { zodValidator } from '@tanstack/zod-adapter'
-
export const Route = createFileRoute('/shop')({
- validateSearch: zodValidator(shopSearchSchema),
+ validateSearch: shopSearchSchema,
component: ShopPage,
})
```
-### Step 4: Read Search Parameters in Components
+### Step 3: Read Search Parameters in Components
Use the route's `useSearch()` hook to access validated and typed search parameters:
@@ -166,12 +175,12 @@ function ShopPage() {
```tsx
const paginationSchema = z.object({
- page: fallback(z.number().min(1), 1).default(1),
- limit: fallback(z.number().min(10).max(100), 20).default(20),
+ page: z.number().min(1).default(1),
+ limit: z.number().min(10).max(100).default(20),
})
export const Route = createFileRoute('/posts')({
- validateSearch: zodValidator(paginationSchema),
+ validateSearch: paginationSchema,
component: PostsPage,
})
@@ -196,16 +205,13 @@ function PostsPage() {
```tsx
const catalogSchema = z.object({
- sort: fallback(z.enum(['name', 'date', 'price']), 'name').default('name'),
- category: fallback(
- z.enum(['electronics', 'clothing', 'books', 'all']),
- 'all',
- ).default('all'),
- ascending: fallback(z.boolean(), true).default(true),
+ sort: z.enum(['name', 'date', 'price']).default('name'),
+ category: z.enum(['electronics', 'clothing', 'books', 'all']).default('all'),
+ ascending: z.boolean().default(true),
})
export const Route = createFileRoute('/catalog')({
- validateSearch: zodValidator(catalogSchema),
+ validateSearch: catalogSchema,
component: CatalogPage,
})
```
@@ -215,27 +221,24 @@ export const Route = createFileRoute('/catalog')({
```tsx
const dashboardSchema = z.object({
// Numbers with validation
- userId: fallback(z.number().positive(), 1).default(1),
- refreshInterval: fallback(z.number().min(1000).max(60000), 5000).default(
- 5000,
- ),
+ userId: z.number().positive().default(1),
+ refreshInterval: z.number().min(1000).max(60000).default(5000),
// Strings with validation
- theme: fallback(z.enum(['light', 'dark']), 'light').default('light'),
+ theme: z.enum(['light', 'dark']).default('light'),
timezone: z.string().optional(),
// Arrays with validation
- selectedIds: fallback(z.number().array(), []).default([]),
- tags: fallback(z.string().array(), []).default([]),
+ selectedIds: z.number().array().default([]),
+ tags: z.string().array().default([]),
// Objects with validation
- filters: fallback(
- z.object({
+ filters: z
+ .object({
status: z.enum(['active', 'inactive']).optional(),
type: z.string().optional(),
- }),
- {},
- ).default({}),
+ })
+ .default({}),
})
```
@@ -245,8 +248,8 @@ const dashboardSchema = z.object({
const reportSchema = z.object({
startDate: z.string().pipe(z.coerce.date()).optional(),
endDate: z.string().pipe(z.coerce.date()).optional(),
- format: fallback(z.enum(['pdf', 'csv', 'excel']), 'pdf').default('pdf'),
- includeCharts: fallback(z.boolean(), true).default(true),
+ format: z.enum(['pdf', 'csv', 'excel']).default('pdf').catch('pdf'),
+ includeCharts: z.boolean().default(true),
})
```
@@ -330,7 +333,7 @@ export const Route = createFileRoute('/example')({
### Problem: Search Parameters Cause TypeScript Errors
-**Cause:** Missing or incorrect schema definition.
+**Cause:** Missing or incorrect schema definition with Zod v3.
**Solution:** Ensure your schema covers all search parameters and use proper types:
@@ -366,7 +369,7 @@ const schema = z.object({
// ✅ Graceful fallback handling
const schema = z.object({
- page: fallback(z.number(), 1).default(1), // Safe fallback to 1
+ page: z.number().default(1).catch(1), // Safe fallback to 1
})
```
diff --git a/docs/router/how-to/share-search-params-across-routes.md b/docs/router/how-to/share-search-params-across-routes.md
index 145d1f089b..e1e24c1e0d 100644
--- a/docs/router/how-to/share-search-params-across-routes.md
+++ b/docs/router/how-to/share-search-params-across-routes.md
@@ -21,7 +21,6 @@ Share parameters across your entire application by validating them in the root r
```tsx
// routes/__root.tsx
import { createRootRoute, Outlet } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
import { z } from 'zod'
const globalSearchSchema = z.object({
@@ -31,7 +30,7 @@ const globalSearchSchema = z.object({
})
export const Route = createRootRoute({
- validateSearch: zodValidator(globalSearchSchema),
+ validateSearch: globalSearchSchema,
component: RootComponent,
})
@@ -50,7 +49,6 @@ function RootComponent() {
```tsx
// routes/products/index.tsx
import { createFileRoute } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
import { z } from 'zod'
const productSearchSchema = z.object({
@@ -59,7 +57,7 @@ const productSearchSchema = z.object({
})
export const Route = createFileRoute('/products/')({
- validateSearch: zodValidator(productSearchSchema),
+ validateSearch: productSearchSchema,
component: ProductsPage,
})
@@ -84,7 +82,6 @@ Share parameters within a section of your app using layout routes:
```tsx
// routes/_authenticated.tsx
import { createFileRoute, Outlet } from '@tanstack/react-router'
-import { zodValidator } from '@tanstack/zod-adapter'
import { z } from 'zod'
const authSearchSchema = z.object({
@@ -94,7 +91,7 @@ const authSearchSchema = z.object({
})
export const Route = createFileRoute('/_authenticated')({
- validateSearch: zodValidator(authSearchSchema),
+ validateSearch: authSearchSchema,
component: AuthenticatedLayout,
})
@@ -181,7 +178,7 @@ function ProductsPage() {
```tsx
// ✅ Root route validates shared parameters
export const Route = createRootRoute({
- validateSearch: zodValidator(globalSearchSchema),
+ validateSearch: globalSearchSchema,
component: RootComponent,
})
```
diff --git a/docs/router/how-to/validate-search-params.md b/docs/router/how-to/validate-search-params.md
index bb141a5a19..5abd435cef 100644
--- a/docs/router/how-to/validate-search-params.md
+++ b/docs/router/how-to/validate-search-params.md
@@ -12,15 +12,14 @@ Add robust validation with custom error messages, complex types, and production-
```tsx
import { createFileRoute, useRouter } from '@tanstack/react-router'
-import { zodValidator, fallback } from '@tanstack/zod-adapter'
import { z } from 'zod'
const productSearchSchema = z.object({
query: z.string().min(1, 'Search query required'),
category: z.enum(['electronics', 'clothing', 'books', 'home']).optional(),
- minPrice: fallback(z.number().min(0, 'Price cannot be negative'), 0),
- maxPrice: fallback(z.number().min(0, 'Price cannot be negative'), 1000),
- inStock: fallback(z.boolean(), true),
+ minPrice: z.number().min(0, 'Price cannot be negative').default(0),
+ maxPrice: z.number().min(0, 'Price cannot be negative').default(1000),
+ inStock: z.boolean().default(true),
tags: z.array(z.string()).optional(),
dateRange: z
.object({
@@ -31,7 +30,7 @@ const productSearchSchema = z.object({
})
export const Route = createFileRoute('/products')({
- validateSearch: zodValidator(productSearchSchema),
+ validateSearch: productSearchSchema,
errorComponent: ({ error }) => {
const router = useRouter()
return (
@@ -80,7 +79,7 @@ TanStack Router supports multiple validation libraries through adapters:
### Zod (Recommended)
-Most popular with excellent TypeScript integration:
+Most popular with excellent TypeScript integration. For Zod v3, use `@tanstack/zod-adapter` for validation:
```tsx
import { zodValidator, fallback } from '@tanstack/zod-adapter'
@@ -99,6 +98,24 @@ export const Route = createFileRoute('/search')({
})
```
+For Zod v4, the adapter is no longer necessary:
+
+```tsx
+import { z } from 'zod'
+
+const searchSchema = z.object({
+ query: z.string().min(1).max(100),
+ page: z.number().int().positive().default(1),
+ sortBy: z.enum(['name', 'date', 'relevance']).optional(),
+ filters: z.array(z.string()).optional(),
+})
+
+export const Route = createFileRoute('/search')({
+ validateSearch: searchSchema,
+ component: SearchPage,
+})
+```
+
### Valibot
Lightweight alternative with modular design:
diff --git a/docs/router/installation/manual.md b/docs/router/installation/manual.md
index 76d1f1fe6a..e2cfcabcf3 100644
--- a/docs/router/installation/manual.md
+++ b/docs/router/installation/manual.md
@@ -204,7 +204,7 @@ function About() {
```tsx title="src/main.tsx"
/* @refresh reload */
-import { render } from 'solid-js/web'
+import { render } from '@solidjs/web'
import { RouterProvider, createRouter } from '@tanstack/solid-router'
// Import the generated route tree
@@ -319,7 +319,7 @@ if (!rootElement.innerHTML) {
```tsx
/* @refresh reload */
-import { render } from 'solid-js/web'
+import { render } from '@solidjs/web'
import {
Outlet,
RouterProvider,
diff --git a/docs/router/quick-start.md b/docs/router/quick-start.md
index 69ec50c538..a3571756df 100644
--- a/docs/router/quick-start.md
+++ b/docs/router/quick-start.md
@@ -9,8 +9,8 @@ The fastest way to get started with TanStack Router is to scaffold a new project
-react: create-tsrouter-app@latest
-solid: create-tsrouter-app@latest --framework solid
+react: @tanstack/cli create --router-only
+solid: @tanstack/cli create --router-only --framework solid
@@ -25,7 +25,7 @@ The CLI will guide you through a short series of prompts to customize your setup
Once complete, a new project will be generated with TanStack Router installed and ready to use.
> [!TIP]
-> For full details on available options and templates, visit the [`create-tsrouter-app` documentation](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app).
+> For full details on available options and templates, visit the [`@tanstack/cli` documentation](https://github.com/TanStack/cli).
## Routing Options
@@ -35,23 +35,37 @@ TanStack Router supports both file-based and code-based route configurations. Yo
The file-based approach is the recommended option for most projects. It automatically creates routes based on your file structure, giving you the best mix of performance, simplicity, and developer experience.
-
+For more details, see the [file-based routing documentation](./routing/file-based-routing.md) or
-react: create-tsrouter-app@latest my-app --template file-router
-solid: create-tsrouter-app@latest my-app --framework solid --template file-router
+
-
+# React
+
+[explore the live example](https://tanstack.com/router/latest/docs/framework/react/examples/basic-file-based)
+
+# Solid
+
+[explore the live example](https://tanstack.com/router/latest/docs/framework/solid/examples/basic-file-based)
+
+
### Code-Based Route Configuration
If you prefer to define routes programmatically, you can use the code-based route configuration. This approach gives you full control over routing logic.
-
+For more details, see the [code-based routing documentation](./routing/code-based-routing.md) or
-react: create-tsrouter-app@latest my-app
-solid: create-tsrouter-app@latest my-app --framework solid
+
-
+# React
+
+[explore the live example](https://tanstack.com/router/latest/docs/framework/react/examples/basic)
+
+# Solid
+
+[explore the live example](https://tanstack.com/router/latest/docs/framework/solid/examples/basic)
+
+
With either approach, navigate to your project directory and start the development server.
diff --git a/docs/start/framework/react/guide/cdn-asset-urls.md b/docs/start/framework/react/guide/cdn-asset-urls.md
index 977c030c68..745250b821 100644
--- a/docs/start/framework/react/guide/cdn-asset-urls.md
+++ b/docs/start/framework/react/guide/cdn-asset-urls.md
@@ -5,13 +5,15 @@ title: CDN Asset URLs
# CDN Asset URLs
-> **Experimental:** `transformAssetUrls` is experimental and subject to change.
+> **Experimental:** `transformAssets` is experimental and subject to change.
-When deploying to production, you may want to serve your static assets (JavaScript, CSS) from a CDN. The `transformAssetUrls` option on `createStartHandler` lets you rewrite asset URLs at runtime — for example, prepending a CDN origin that is only known when the server starts.
+When deploying to production, you may want to serve your static assets (JavaScript, CSS) from a CDN. The `transformAssets` option on `createStartHandler` lets you rewrite asset URLs at runtime - for example, prepending a CDN origin that is only known when the server starts.
+
+`transformAssetUrls` still works, but it is deprecated and now delegates to `transformAssets` with a development warning.
## Why Runtime URL Rewriting?
-Vite's `base` config is evaluated at build time. If your CDN URL is determined at deploy time (via environment variables, dynamic configuration, etc.), you need a way to rewrite URLs at runtime. `transformAssetUrls` solves this for the URLs that TanStack Start manages in its manifest:
+Vite's `base` config is evaluated at build time. If your CDN URL is determined at deploy time (via environment variables, dynamic configuration, etc.), you need a way to rewrite URLs at runtime. `transformAssets` solves this for the URLs that TanStack Start manages in its manifest:
- `` tags (JS preloads)
- `` tags (CSS)
@@ -33,7 +35,7 @@ import { createServerEntry } from '@tanstack/react-start/server-entry'
const handler = createStartHandler({
handler: defaultStreamHandler,
- transformAssetUrls: process.env.CDN_ORIGIN || '',
+ transformAssets: process.env.CDN_ORIGIN || '',
})
export default createServerEntry({ fetch: handler })
@@ -43,9 +45,9 @@ If `CDN_ORIGIN` is `https://cdn.example.com` and an asset URL is `/assets/index-
When the string is empty (or not set), the URLs are left unchanged.
-### Callback
+### Object Shorthand (Prefix + CrossOrigin)
-For more control, pass a callback that receives `{ url, type }` and returns a new URL (or a `Promise` of one). By default, the transformed manifest is cached after the first request (`cache: true`), so the callback only runs once in production:
+If you also need to set `crossOrigin` on manifest-managed `` tags, use the object shorthand with `prefix` and `crossOrigin`:
```tsx
// src/server.ts
@@ -57,10 +59,54 @@ import { createServerEntry } from '@tanstack/react-start/server-entry'
const handler = createStartHandler({
handler: defaultStreamHandler,
- transformAssetUrls: ({ url, type }) => {
- // Only rewrite JS and CSS, leave client entry unchanged
- if (type === 'clientEntry') return url
- return `https://cdn.example.com${url}`
+ transformAssets: {
+ prefix: process.env.CDN_ORIGIN || '',
+ crossOrigin: 'anonymous',
+ },
+})
+
+export default createServerEntry({ fetch: handler })
+```
+
+`crossOrigin` accepts either a single value applied to all asset kinds, or a per-kind record (matching the `HeadContent assetCrossOrigin` shape):
+
+```tsx
+transformAssets: {
+ prefix: 'https://cdn.example.com',
+ crossOrigin: {
+ modulepreload: 'anonymous',
+ stylesheet: 'use-credentials',
+ },
+}
+```
+
+Kinds not listed in the per-kind record receive no `crossOrigin` attribute. Like the string shorthand, the object shorthand is always cached (`cache: true`).
+
+### Callback
+
+For more control, pass a callback that receives `{ kind, url }` and returns a string, or `{ href, crossOrigin? }` (or a `Promise` of either). By default, the transformed manifest is cached after the first request (`cache: true`), so the callback only runs once in production:
+
+```tsx
+// src/server.ts
+import {
+ createStartHandler,
+ defaultStreamHandler,
+} from '@tanstack/react-start/server'
+import { createServerEntry } from '@tanstack/react-start/server-entry'
+
+const handler = createStartHandler({
+ handler: defaultStreamHandler,
+ transformAssets: ({ kind, url }) => {
+ const href = `https://cdn.example.com${url}`
+
+ if (kind === 'modulepreload') {
+ return {
+ href,
+ crossOrigin: 'anonymous',
+ }
+ }
+
+ return { href }
},
})
@@ -69,17 +115,19 @@ export default createServerEntry({ fetch: handler })
If you need per-request behavior (for example, choosing a CDN based on a header), use the object form with `cache: false`.
-The `type` parameter tells you what kind of asset URL is being transformed:
+The `kind` parameter tells you what kind of asset URL is being transformed:
-| `type` | Description |
+| `kind` | Description |
| ----------------- | ---------------------------------------------------- |
| `'modulepreload'` | JS module preload URL (``) |
| `'stylesheet'` | CSS stylesheet URL (``) |
| `'clientEntry'` | Client entry module URL (used in `import('...')`) |
+`crossOrigin` applies to manifest-managed link tags. For the client entry, returning `{ href }` is equivalent to returning a string.
+
### Object Form (Explicit Cache Control)
-For per-request transforms — where the CDN URL depends on request-specific data like headers — use the object form with `cache: false`:
+For per-request transforms - where the CDN URL depends on request-specific data like headers - use the object form with `cache: false`:
```tsx
// src/server.ts
@@ -92,14 +140,22 @@ import { getRequest } from '@tanstack/react-start/server'
const handler = createStartHandler({
handler: defaultStreamHandler,
- transformAssetUrls: {
- transform: ({ url, type }) => {
+ transformAssets: {
+ transform: ({ kind, url }) => {
const region = getRequest().headers.get('x-region') || 'us'
const cdnBase =
region === 'eu'
? 'https://cdn-eu.example.com'
: 'https://cdn-us.example.com'
- return `${cdnBase}${url}`
+
+ if (kind === 'modulepreload') {
+ return {
+ href: `${cdnBase}${url}`,
+ crossOrigin: 'anonymous',
+ }
+ }
+
+ return { href: `${cdnBase}${url}` }
},
cache: false,
},
@@ -110,34 +166,43 @@ export default createServerEntry({ fetch: handler })
The object form accepts:
-| Property | Type | Description |
-| ----------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
-| `transform` | `string \| (asset) => string \| Promise` | A string prefix or callback, same as the shorthand forms above. |
-| `createTransform` | `(ctx: { warmup: true } \| { warmup: false; request: Request }) => (asset) => string \| Promise` | Async factory that runs once per manifest computation and returns a per-asset transform. Mutually exclusive with `transform`. |
-| `cache` | `boolean` | Whether to cache the transformed manifest. Defaults to `true`. |
-| `warmup` | `boolean` | When `true`, warms up the cached manifest on server startup (prod only). Defaults to `false`. |
+| Property | Type | Description |
+| ----------------- | ------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
+| `transform` | `string \| (asset) => string \| { href, crossOrigin? } \| Promise<...>` | A string prefix or callback, same as the shorthand forms above. |
+| `createTransform` | `(ctx: { warmup: true } \| { warmup: false; request: Request }) => (asset) => string \| { href, crossOrigin? } \| Promise<...>` | Async factory that runs once per manifest computation and returns a per-asset transform. Mutually exclusive with `transform`. |
+| `cache` | `boolean` | Whether to cache the transformed manifest. Defaults to `true`. |
+| `warmup` | `boolean` | When `true`, warms up the cached manifest on server startup (prod only). Defaults to `false`. |
If you need to do async work once per manifest computation (e.g. fetch a CDN origin from a service) and then transform many URLs, prefer `createTransform`:
```ts
-transformAssetUrls: {
+transformAssets: {
cache: false,
async createTransform(ctx) {
if (ctx.warmup) {
- // optional: return a default transform during warmup
- return ({ url }) => url
+ return ({ url }) => ({ href: url })
}
const region = ctx.request.headers.get('x-region') || 'us'
const cdnBase = await fetchCdnBaseForRegion(region)
- return ({ url }) => `${cdnBase}${url}`
+
+ return ({ kind, url }) => {
+ if (kind === 'modulepreload') {
+ return {
+ href: `${cdnBase}${url}`,
+ crossOrigin: 'anonymous',
+ }
+ }
+
+ return { href: `${cdnBase}${url}` }
+ }
},
}
```
## Caching Behavior
-By default, **all forms** of `transformAssetUrls` cache the transformed manifest after the first request (`cache: true`). This means the transform function runs once on the first request, and the result is reused for every subsequent request in production.
+By default, all forms of `transformAssets` cache the transformed manifest after the first request (`cache: true`). This means the transform function runs once on the first request, and the result is reused for every subsequent request in production.
| Form | Default cache | Behavior |
| -------------------------------------- | ------------- | ---------------------------------------------------------- |
@@ -154,7 +219,7 @@ If you're using the object form with `cache: true`, you can set `warmup: true`
to compute the transformed manifest in the background at server startup.
```ts
-transformAssetUrls: {
+transformAssets: {
transform: process.env.CDN_ORIGIN || '',
cache: true,
warmup: true,
@@ -165,11 +230,34 @@ This has no effect in development mode, or when `cache: false`.
> **Note:** In development mode (`TSS_DEV_SERVER`), caching is always skipped regardless of the `cache` setting, so you always get fresh manifests.
+## With `HeadContent assetCrossOrigin`
+
+If you want to set cross-origin behavior from the app shell instead of the server entry, `HeadContent` also accepts `assetCrossOrigin`:
+
+```tsx
+
+```
+
+or:
+
+```tsx
+
+```
+
+If both `transformAssets` and `assetCrossOrigin` set a cross-origin value, `assetCrossOrigin` overrides the value from `transformAssets`.
+
+`assetCrossOrigin` only applies to manifest-managed `modulepreload` and stylesheet links, not arbitrary links you return from route `head()` functions.
+
## Recommended: Set `base: ''` for Client-Side Navigation
-`transformAssetUrls` rewrites the URLs in the SSR HTML — modulepreload hints, stylesheets, and the client entry script. This means the browser's initial page load fetches all assets from the CDN.
+`transformAssets` rewrites the URLs in the SSR HTML - modulepreload hints, stylesheets, and the client entry script. This means the browser's initial page load fetches all assets from the CDN.
-However, when users navigate client-side (e.g., clicking a ``), TanStack Router lazy-loads route chunks using `import()` calls with paths that were baked in at **build time** by Vite. By default, Vite uses `base: '/'`, which produces absolute paths like `/assets/about-abc123.js`. These resolve against the **app server's origin**, not the CDN — even though the entry module was loaded from the CDN.
+However, when users navigate client-side (e.g., clicking a ``), TanStack Router lazy-loads route chunks using `import()` calls with paths that were baked in at build time by Vite. By default, Vite uses `base: '/'`, which produces absolute paths like `/assets/about-abc123.js`. These resolve against the app server's origin, not the CDN - even though the entry module was loaded from the CDN.
To fix this, set `base: ''` in your Vite config:
@@ -181,29 +269,29 @@ export default defineConfig({
})
```
-With `base: ''`, Vite generates **relative** import paths for client-side chunks. Since the client entry module was loaded from the CDN (thanks to `transformAssetUrls`), all relative `import()` calls resolve against the CDN origin. This ensures that lazy-loaded route chunks during client-side navigation are also served from the CDN.
+With `base: ''`, Vite generates relative import paths for client-side chunks. Since the client entry module was loaded from the CDN (thanks to `transformAssets`), all relative `import()` calls resolve against the CDN origin. This ensures that lazy-loaded route chunks during client-side navigation are also served from the CDN.
-Using an empty string rather than `'./'` is important — both produce relative client-side imports, but `base: ''` preserves the correct root-relative paths (`/assets/...`) in the SSR manifest so that `transformAssetUrls` can properly prepend the CDN origin.
+Using an empty string rather than `'./'` is important - both produce relative client-side imports, but `base: ''` preserves the correct root-relative paths (`/assets/...`) in the SSR manifest so that `transformAssets` can properly prepend the CDN origin.
-| `base` setting | SSR assets (initial load) | Client-side navigation chunks |
-| --------------- | ------------------------------ | ------------------------------ |
-| `'/'` (default) | CDN (via `transformAssetUrls`) | App server |
-| `''` | CDN (via `transformAssetUrls`) | CDN (relative to entry module) |
+| `base` setting | SSR assets (initial load) | Client-side navigation chunks |
+| --------------- | --------------------------- | ------------------------------ |
+| `'/'` (default) | CDN (via `transformAssets`) | App server |
+| `''` | CDN (via `transformAssets`) | CDN (relative to entry module) |
-> **Tip:** `base: ''` is recommended whenever you use `transformAssetUrls` so that all assets — both on initial load and during client-side navigation — are consistently served from the CDN.
+> **Tip:** `base: ''` is recommended whenever you use `transformAssets` so that all assets - both on initial load and during client-side navigation - are consistently served from the CDN.
-## What This Does NOT Cover
+## What This Does Not Cover
-`transformAssetUrls` only rewrites URLs in the TanStack Start manifest — the tags emitted during SSR for preloading and bootstrapping the application.
+`transformAssets` only rewrites URLs in the TanStack Start manifest - the tags emitted during SSR for preloading and bootstrapping the application.
-It does **not** rewrite asset URLs that are imported directly in your components:
+It does not rewrite asset URLs imported directly in your components:
```tsx
// This import resolves to a URL at build time by Vite
import logo from './logo.svg'
function Header() {
- return // This URL is NOT affected by transformAssetUrls
+ return // This URL is NOT affected by transformAssets
}
```
diff --git a/docs/start/framework/react/guide/hosting.md b/docs/start/framework/react/guide/hosting.md
index b37c258ad2..26e2e0db66 100644
--- a/docs/start/framework/react/guide/hosting.md
+++ b/docs/start/framework/react/guide/hosting.md
@@ -190,8 +190,8 @@ tool](https://docs.netlify.com/start/quickstarts/deploy-from-ai-code-generation-
-
-
+
+
@@ -288,7 +288,7 @@ npm run start
### Bun
> [!IMPORTANT]
-> Currently, the Bun specific deployment guidelines only work with React 19. If you are using React 18, please refer to the [Node.js](#nodejs--railway--docker) deployment guidelines.
+> Currently, the Bun specific deployment guidelines only work with React 19. If you are using React 18, please refer to the [Node.js](#nodejs--docker) deployment guidelines.
Make sure that your `react` and `react-dom` packages are set to version 19.0.0 or higher in your `package.json` file. If not, run the following command to upgrade the packages:
diff --git a/docs/start/framework/react/migrate-from-next-js.md b/docs/start/framework/react/migrate-from-next-js.md
index ea82a4e850..3517360743 100644
--- a/docs/start/framework/react/migrate-from-next-js.md
+++ b/docs/start/framework/react/migrate-from-next-js.md
@@ -52,16 +52,16 @@ rm postcss.config.* next.config.*
### 2. Install Required Dependencies
-TanStack Start leverages [Vite](https://vite.dev) and TanStack Router:
+TanStack Start leverages Tanstack Router, [Vite](https://vite.dev), and a vite deployment plugin e.g. [nitro](https://nitro.build/).
```sh
-npm i @tanstack/react-router @tanstack/react-start
+npm i @tanstack/react-router @tanstack/react-start nitro vite @vitejs/plugin-react
```
-For Tailwind CSS and resolving imports using path aliases:
+For Tailwind CSS:
```sh
-npm i -D vite @vitejs/plugin-react @tailwindcss/vite tailwindcss vite-tsconfig-paths
+npm i -D @tailwindcss/vite tailwindcss
```
### 3. Update Project Configuration
@@ -88,17 +88,19 @@ Now that you've installed the necessary dependencies, update your project config
import { defineConfig } from 'vite'
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'
-import tsconfigPaths from 'vite-tsconfig-paths'
import tailwindcss from '@tailwindcss/vite'
+import { nitro } from 'nitro/vite'
export default defineConfig({
server: {
port: 3000,
},
+ resolve: {
+ // Enables Vite to resolve imports using path aliases.
+ tsconfigPaths: true,
+ },
plugins: [
tailwindcss(),
- // Enables Vite to resolve imports using path aliases.
- tsconfigPaths(),
tanstackStart({
srcDirectory: 'src', // This is the default
router: {
@@ -107,6 +109,7 @@ export default defineConfig({
},
}),
viteReact(),
+ nitro(),
],
})
```
diff --git a/docs/start/framework/solid/build-from-scratch.md b/docs/start/framework/solid/build-from-scratch.md
index 1e10b29ae5..5ca328f24c 100644
--- a/docs/start/framework/solid/build-from-scratch.md
+++ b/docs/start/framework/solid/build-from-scratch.md
@@ -164,7 +164,7 @@ import {
HeadContent,
Scripts,
} from '@tanstack/solid-router'
-import { HydrationScript } from 'solid-js/web'
+import { HydrationScript } from '@solidjs/web'
export const Route = createRootRoute({
head: () => ({
diff --git a/docs/start/framework/solid/guide/client-entry-point.md b/docs/start/framework/solid/guide/client-entry-point.md
index b73408e8e4..c44d7a9a47 100644
--- a/docs/start/framework/solid/guide/client-entry-point.md
+++ b/docs/start/framework/solid/guide/client-entry-point.md
@@ -12,7 +12,7 @@ Getting our html to the client is only half the battle. Once there, we need to h
```tsx
// src/client.tsx
-import { hydrate } from 'solid-js/web'
+import { hydrate } from '@solidjs/web'
import { StartClient, hydrateStart } from '@tanstack/solid-start/client'
hydrateStart().then((router) => {
@@ -29,7 +29,7 @@ You can wrap your client entry point with error boundaries to handle client-side
```tsx
// src/client.tsx
import { StartClient } from '@tanstack/solid-start/client'
-import { hydrate } from 'solid-js/web'
+import { hydrate } from '@solidjs/web'
import { ErrorBoundary } from './components/ErrorBoundary'
hydrate(
@@ -49,7 +49,7 @@ You may want different behavior in development vs production:
```tsx
// src/client.tsx
import { StartClient } from '@tanstack/solid-start/client'
-import { hydrate } from 'solid-js/web'
+import { hydrate } from '@solidjs/web'
const App = (
<>
diff --git a/docs/start/framework/solid/guide/hydration-errors.md b/docs/start/framework/solid/guide/hydration-errors.md
index 75e44280c9..75e7d59c82 100644
--- a/docs/start/framework/solid/guide/hydration-errors.md
+++ b/docs/start/framework/solid/guide/hydration-errors.md
@@ -93,7 +93,7 @@ function SetTimeZoneCookie() {
```tsx
import { ClientOnly } from '@tanstack/solid-router'
-import { NoHydration } from 'solid-js/web'
+import { NoHydration } from '@solidjs/web'
—}>
diff --git a/e2e/e2e-utils/src/devServerWarmup.ts b/e2e/e2e-utils/src/devServerWarmup.ts
new file mode 100644
index 0000000000..970711120d
--- /dev/null
+++ b/e2e/e2e-utils/src/devServerWarmup.ts
@@ -0,0 +1,69 @@
+import { chromium } from '@playwright/test'
+import type { Page } from '@playwright/test'
+
+export async function waitForServer(url: string) {
+ const start = Date.now()
+
+ while (Date.now() - start < 30_000) {
+ const controller = new AbortController()
+ const timer = setTimeout(() => controller.abort(), 5_000)
+
+ try {
+ const res = await fetch(url, {
+ redirect: 'manual',
+ signal: controller.signal,
+ })
+
+ if (res.status >= 200 && res.status < 400) {
+ return
+ }
+ } catch {
+ // ignore aborted/network errors
+ } finally {
+ clearTimeout(timer)
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 250))
+ }
+
+ throw new Error(`Timed out waiting for dev server at ${url}`)
+}
+
+export async function preOptimizeDevServer(opts: {
+ baseURL: string
+ readyTestId?: string
+ warmup?: (page: Page) => Promise
+}) {
+ const browser = await chromium.launch()
+ const context = await browser.newContext()
+ const page = await context.newPage()
+
+ try {
+ await page.goto(`${opts.baseURL}/`, { waitUntil: 'domcontentloaded' })
+
+ if (opts.readyTestId) {
+ await page.getByTestId(opts.readyTestId).waitFor({ state: 'visible' })
+ }
+
+ await page.waitForLoadState('networkidle')
+
+ await opts.warmup?.(page)
+
+ for (let i = 0; i < 40; i++) {
+ const currentUrl = page.url()
+ await page.waitForTimeout(250)
+
+ if (page.url() === currentUrl) {
+ await page.waitForTimeout(250)
+ if (page.url() === currentUrl) {
+ return
+ }
+ }
+ }
+
+ throw new Error('Dev server did not reach a stable URL after warmup')
+ } finally {
+ await context.close()
+ await browser.close()
+ }
+}
diff --git a/e2e/e2e-utils/src/index.ts b/e2e/e2e-utils/src/index.ts
index 2a4219ddcf..f1c489c871 100644
--- a/e2e/e2e-utils/src/index.ts
+++ b/e2e/e2e-utils/src/index.ts
@@ -3,5 +3,6 @@ export { localDummyServer } from './localDummyServer'
export { toRuntimePath } from './to-runtime-path'
export { resolveRuntimeSuffix } from './resolve-runtime-suffix'
export { e2eStartDummyServer, e2eStopDummyServer } from './e2eSetupTeardown'
+export { preOptimizeDevServer, waitForServer } from './devServerWarmup'
export type { Post } from './posts'
export { test } from './fixture'
diff --git a/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts b/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts
index ab0bb4bc99..06b90f6528 100644
--- a/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts
+++ b/e2e/react-router/basepath-file-based/tests/scroll-restoration-session-storage-error.test.ts
@@ -1,25 +1,10 @@
/* eslint-disable */
import { expect, test } from '@playwright/test'
-import type { Page } from '@playwright/test'
-
-const trackConsole = (page: Page) => {
- const consoleWarnings: Array = []
-
- page.on('console', (msg) => {
- if (msg.type() === 'warning') {
- consoleWarnings.push(msg.text())
- }
- })
-
- return consoleWarnings
-}
test.describe('Scroll Restoration with Session Storage Error', () => {
test('should not crash when sessionStorage.setItem throws an error', async ({
page,
}) => {
- const consoleWarnings = trackConsole(page)
-
await page.goto('/app/scroll-error')
await page.waitForLoadState('networkidle')
@@ -32,20 +17,9 @@ test.describe('Scroll Restoration with Session Storage Error', () => {
await page.evaluate(() => window.scrollTo(0, 200))
await page.waitForTimeout(150)
- await page.click('a[href="/app/about"]')
+ await page.reload()
await page.waitForLoadState('networkidle')
- await page.goBack()
- await page.waitForLoadState('networkidle')
-
- expect(
- consoleWarnings.some((warning) =>
- warning.includes(
- '[ts-router] Could not persist scroll restoration state to sessionStorage.',
- ),
- ),
- ).toBeTruthy()
-
const heading = page.locator('h1:has-text("Scroll Error Test")')
await expect(heading).toBeVisible()
@@ -53,11 +27,9 @@ test.describe('Scroll Restoration with Session Storage Error', () => {
expect(scrollPosition).not.toBe(200)
})
- test('should surface warning when sessionStorage quota is exceeded', async ({
+ test('should not crash when sessionStorage quota is exceeded', async ({
page,
}) => {
- const consoleWarnings = trackConsole(page)
-
await page.goto('/app/scroll-error')
await page.waitForLoadState('networkidle')
@@ -78,20 +50,9 @@ test.describe('Scroll Restoration with Session Storage Error', () => {
await page.evaluate(() => window.scrollTo(0, 200))
await page.waitForTimeout(150)
- await page.click('a[href="/app/about"]')
+ await page.reload()
await page.waitForLoadState('networkidle')
- await page.goBack()
- await page.waitForLoadState('networkidle')
-
- expect(
- consoleWarnings.some((warning) =>
- warning.includes(
- '[ts-router] Could not persist scroll restoration state to sessionStorage.',
- ),
- ),
- ).toBeTruthy()
-
const heading = page.locator('h1:has-text("Scroll Error Test")')
await expect(heading).toBeVisible()
diff --git a/e2e/react-router/basic-file-based-code-splitting/src/vite-env.d.ts b/e2e/react-router/basic-file-based-code-splitting/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic-file-based-code-splitting/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/basic-file-based/src/vite-env.d.ts b/e2e/react-router/basic-file-based/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic-file-based/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/basic-file-based/tests/app.spec.ts b/e2e/react-router/basic-file-based/tests/app.spec.ts
index 6c8b8068fa..ae87d350ce 100644
--- a/e2e/react-router/basic-file-based/tests/app.spec.ts
+++ b/e2e/react-router/basic-file-based/tests/app.spec.ts
@@ -268,6 +268,8 @@ async function structuralSharingTest(page: Page, enabled: boolean) {
test('structural sharing disabled', async ({ page }) => {
await structuralSharingTest(page, false)
+ expect(await getRenderCount(page)).toBe(2)
+ await page.getByTestId('link').click()
expect(await getRenderCount(page)).toBeGreaterThan(2)
})
diff --git a/e2e/react-router/basic-react-query-file-based/src/vite-env.d.ts b/e2e/react-router/basic-react-query-file-based/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic-react-query-file-based/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/basic-react-query/src/vite-env.d.ts b/e2e/react-router/basic-react-query/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic-react-query/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/basic-scroll-restoration/package.json b/e2e/react-router/basic-scroll-restoration/package.json
index 2d6ab9dd36..d9a76d8f03 100644
--- a/e2e/react-router/basic-scroll-restoration/package.json
+++ b/e2e/react-router/basic-scroll-restoration/package.json
@@ -26,6 +26,7 @@
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.3",
"@vitejs/plugin-react": "^6.0.1",
- "vite": "^8.0.0"
+ "vite": "^8.0.0",
+ "typescript": "~5.9.0"
}
}
diff --git a/e2e/react-router/basic-scroll-restoration/src/vite-env.d.ts b/e2e/react-router/basic-scroll-restoration/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic-scroll-restoration/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/basic-virtual-file-based/src/vite-env.d.ts b/e2e/react-router/basic-virtual-file-based/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic-virtual-file-based/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/react-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic-virtual-named-export-config-file-based/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/basic/src/vite-env.d.ts b/e2e/react-router/basic/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/basic/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/generator-cli-only/src/vite-env.d.ts b/e2e/react-router/generator-cli-only/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/generator-cli-only/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/i18n-paraglide/package.json b/e2e/react-router/i18n-paraglide/package.json
index 1d4f8d0b4c..0316269242 100644
--- a/e2e/react-router/i18n-paraglide/package.json
+++ b/e2e/react-router/i18n-paraglide/package.json
@@ -26,7 +26,7 @@
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.3",
"@vitejs/plugin-react": "^6.0.1",
- "typescript": "^5.7.2",
+ "typescript": "^6.0.2",
"vite": "^8.0.0"
}
}
diff --git a/e2e/react-router/i18n-paraglide/src/vite-env.d.ts b/e2e/react-router/i18n-paraglide/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/i18n-paraglide/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/js-only-file-based/src/vite-env.d.ts b/e2e/react-router/js-only-file-based/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/js-only-file-based/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/rspack-basic-file-based/package.json b/e2e/react-router/rspack-basic-file-based/package.json
index e276a82cf1..743a3042f6 100644
--- a/e2e/react-router/rspack-basic-file-based/package.json
+++ b/e2e/react-router/rspack-basic-file-based/package.json
@@ -27,6 +27,6 @@
"@types/react-dom": "^19.0.3",
"postcss": "^8.5.1",
"tailwindcss": "^4.2.2",
- "typescript": "^5.7.2"
+ "typescript": "^6.0.2"
}
}
diff --git a/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/rspack-basic-file-based/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/rspack-basic-file-based/tsconfig.json b/e2e/react-router/rspack-basic-file-based/tsconfig.json
index 76f578eb54..2f5f67eac7 100644
--- a/e2e/react-router/rspack-basic-file-based/tsconfig.json
+++ b/e2e/react-router/rspack-basic-file-based/tsconfig.json
@@ -12,6 +12,6 @@
"useDefineForClassFields": true,
"allowJs": true
},
- "include": ["src", "playwright.config.ts", "tests"],
+ "include": ["src", "tests"],
"exclude": ["node_modules", "dist"]
}
diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json
index d4ca0606f1..ad6d498d6a 100644
--- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json
+++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/package.json
@@ -28,6 +28,6 @@
"@types/react-dom": "^19.0.3",
"postcss": "^8.5.1",
"tailwindcss": "^4.2.2",
- "typescript": "^5.7.2"
+ "typescript": "^6.0.2"
}
}
diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts
new file mode 100644
index 0000000000..11f02fe2a0
--- /dev/null
+++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/src/vite-env.d.ts
@@ -0,0 +1 @@
+///
diff --git a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json
index 7dc6d51cf9..a32f07a8ef 100644
--- a/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json
+++ b/e2e/react-router/rspack-basic-virtual-named-export-config-file-based/tsconfig.json
@@ -12,6 +12,6 @@
"useDefineForClassFields": true,
"allowJs": true
},
- "include": ["src", "playwright.config.ts", "tests", "./routes.ts"],
+ "include": ["src", "tests", "./routes.ts"],
"exclude": ["node_modules", "dist"]
}
diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts
index 6664a9ddf7..a4dc8750b3 100644
--- a/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts
+++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routeTree.gen.ts
@@ -16,6 +16,8 @@ import { Route as testsPageWithSearchRouteImport } from './routes/(tests)/page-w
import { Route as testsNormalPageRouteImport } from './routes/(tests)/normal-page'
import { Route as testsLazyWithLoaderPageRouteImport } from './routes/(tests)/lazy-with-loader-page'
import { Route as testsLazyPageRouteImport } from './routes/(tests)/lazy-page'
+import { Route as testsIssue7040TargetRouteImport } from './routes/(tests)/issue-7040-target'
+import { Route as testsIssue7040SourceRouteImport } from './routes/(tests)/issue-7040-source'
const testsVirtualPageLazyRouteImport = createFileRoute(
'/(tests)/virtual-page',
@@ -59,9 +61,21 @@ const testsLazyPageRoute = testsLazyPageRouteImport
getParentRoute: () => rootRouteImport,
} as any)
.lazy(() => import('./routes/(tests)/lazy-page.lazy').then((d) => d.Route))
+const testsIssue7040TargetRoute = testsIssue7040TargetRouteImport.update({
+ id: '/(tests)/issue-7040-target',
+ path: '/issue-7040-target',
+ getParentRoute: () => rootRouteImport,
+} as any)
+const testsIssue7040SourceRoute = testsIssue7040SourceRouteImport.update({
+ id: '/(tests)/issue-7040-source',
+ path: '/issue-7040-source',
+ getParentRoute: () => rootRouteImport,
+} as any)
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
+ '/issue-7040-source': typeof testsIssue7040SourceRoute
+ '/issue-7040-target': typeof testsIssue7040TargetRoute
'/lazy-page': typeof testsLazyPageRoute
'/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute
'/normal-page': typeof testsNormalPageRoute
@@ -70,6 +84,8 @@ export interface FileRoutesByFullPath {
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
+ '/issue-7040-source': typeof testsIssue7040SourceRoute
+ '/issue-7040-target': typeof testsIssue7040TargetRoute
'/lazy-page': typeof testsLazyPageRoute
'/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute
'/normal-page': typeof testsNormalPageRoute
@@ -79,6 +95,8 @@ export interface FileRoutesByTo {
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
+ '/(tests)/issue-7040-source': typeof testsIssue7040SourceRoute
+ '/(tests)/issue-7040-target': typeof testsIssue7040TargetRoute
'/(tests)/lazy-page': typeof testsLazyPageRoute
'/(tests)/lazy-with-loader-page': typeof testsLazyWithLoaderPageRoute
'/(tests)/normal-page': typeof testsNormalPageRoute
@@ -89,6 +107,8 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
+ | '/issue-7040-source'
+ | '/issue-7040-target'
| '/lazy-page'
| '/lazy-with-loader-page'
| '/normal-page'
@@ -97,6 +117,8 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo
to:
| '/'
+ | '/issue-7040-source'
+ | '/issue-7040-target'
| '/lazy-page'
| '/lazy-with-loader-page'
| '/normal-page'
@@ -105,6 +127,8 @@ export interface FileRouteTypes {
id:
| '__root__'
| '/'
+ | '/(tests)/issue-7040-source'
+ | '/(tests)/issue-7040-target'
| '/(tests)/lazy-page'
| '/(tests)/lazy-with-loader-page'
| '/(tests)/normal-page'
@@ -114,6 +138,8 @@ export interface FileRouteTypes {
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
+ testsIssue7040SourceRoute: typeof testsIssue7040SourceRoute
+ testsIssue7040TargetRoute: typeof testsIssue7040TargetRoute
testsLazyPageRoute: typeof testsLazyPageRoute
testsLazyWithLoaderPageRoute: typeof testsLazyWithLoaderPageRoute
testsNormalPageRoute: typeof testsNormalPageRoute
@@ -165,11 +191,27 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof testsLazyPageRouteImport
parentRoute: typeof rootRouteImport
}
+ '/(tests)/issue-7040-target': {
+ id: '/(tests)/issue-7040-target'
+ path: '/issue-7040-target'
+ fullPath: '/issue-7040-target'
+ preLoaderRoute: typeof testsIssue7040TargetRouteImport
+ parentRoute: typeof rootRouteImport
+ }
+ '/(tests)/issue-7040-source': {
+ id: '/(tests)/issue-7040-source'
+ path: '/issue-7040-source'
+ fullPath: '/issue-7040-source'
+ preLoaderRoute: typeof testsIssue7040SourceRouteImport
+ parentRoute: typeof rootRouteImport
+ }
}
}
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
+ testsIssue7040SourceRoute: testsIssue7040SourceRoute,
+ testsIssue7040TargetRoute: testsIssue7040TargetRoute,
testsLazyPageRoute: testsLazyPageRoute,
testsLazyWithLoaderPageRoute: testsLazyWithLoaderPageRoute,
testsNormalPageRoute: testsNormalPageRoute,
diff --git a/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx
new file mode 100644
index 0000000000..3c1702a942
--- /dev/null
+++ b/e2e/react-router/scroll-restoration-sandbox-vite/src/routes/(tests)/issue-7040-source.tsx
@@ -0,0 +1,49 @@
+import * as React from 'react'
+import { Link, createFileRoute } from '@tanstack/react-router'
+
+export const Route = createFileRoute('/(tests)/issue-7040-source')({
+ component: Component,
+})
+
+const sectionCount = 180
+
+function Component() {
+ return (
+
+
+
issue-7040-source
+
+ Tall page for reproducing the scroll restoration race.
+
@@ -14,24 +22,18 @@ function HomeComponent() {
Otherwise known as NOT first-load tests, rather known as navigation
tests.
- {(
- [
- linkOptions({ to: '/normal-page' }),
- linkOptions({ to: '/lazy-page' }),
- linkOptions({ to: '/virtual-page' }),
- linkOptions({ to: '/lazy-with-loader-page' }),
- linkOptions({ to: '/page-with-search', search: { where: 'footer' } }),
- ] as const
- ).map((options, i) => (
-