Open History to see the last commit
1---
2id: tanstack-query
3title: TanStack Query
4description: Use TanStack Query with TanStack Start for request-isolated SSR, hydration, route preloading, streaming, and mutation invalidation.
5---
6β
7TanStack Start uses Router loaders to coordinate navigation. TanStack Query can own the fetched data, freshness, and mutation state. Use them together when your application needs a query cache across routes, background updates, or mutation-driven invalidation.
8β
9The [React Query example](../examples/start-basic-react-query) includes a `/preferences` page that reads and updates a display name stored in a cookie. Its [tests](https://github.com/TanStack/router/blob/main/examples/react/start-basic-react-query/tests/preferences.spec.ts) check server-rendered data, isolation between requests, hydration without a duplicate read, and invalidation after a server function. The preference cookie is not an authentication mechanism.
10β
11## Install and create a QueryClient per router
12β
13Install `@tanstack/react-query` and `@tanstack/react-router-ssr-query`. The example uses Query 5.102 or newer, including `queryClient.query`. See the [integration reference](/router/latest/docs/integrations/query) for its options.
14β
15```tsx title="src/router.tsx"
16import { QueryClient } from '@tanstack/react-query'
17import { createRouter } from '@tanstack/react-router'
18import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query'
19import { routeTree } from './routeTree.gen'
20β
21export function getRouter() {
22 const queryClient = new QueryClient({
23 defaultOptions: { queries: { staleTime: 30_000 } },
24 })
25 const router = createRouter({
26 routeTree,
27 context: { queryClient },
28 defaultPreload: 'intent',
29 defaultPreloadStaleTime: 0,
30 })
31β
32 setupRouterSsrQueryIntegration({ router, queryClient })
33 return router
34}
35```
36β
37Create the client inside `getRouter`, not at module scope. Start creates a router for each SSR request. A process-wide QueryClient could reuse one reader's cached data in another reader's HTML. The browser then keeps the client attached to its router during navigation.
38β
39Declare `queryClient: QueryClient` in the root route's `createRootRouteWithContext` type so child loaders can access it. The integration supplies the Query provider and handles SSR dehydration, hydration, and streaming. Do not add a second QueryClient or independently dehydrate the same cache. If you already own the provider wrapper, use the integration's `wrapQueryClient: false` option.
40β
41`defaultPreloadStaleTime: 0` lets Query decide whether a preload needs data. The example's 30-second Query `staleTime` prevents an immediate repeat read when the browser receives fresh SSR data. Choose the freshness window for your application, rather than treating 30 seconds as a universal setting.
42β
43## Share query options between the loader and component
44β
45Keep a query's key and function together. Privileged reads belong in a server function, because a normal route loader can also run in the browser during navigation.
46β
47```tsx title="src/utils/preferences.ts"
48import { queryOptions } from '@tanstack/react-query'
49import { createServerFn } from '@tanstack/react-start'
50import { getCookie, setResponseHeader } from '@tanstack/react-start/server'
51β
52export const getReaderName = createServerFn({ method: 'GET' }).handler(() => {
53 setResponseHeader('Cache-Control', 'private, no-store')
54 return getCookie('reader-name') || 'Guest'
55})
56β
57export const readerNameOptions = queryOptions({
58 queryKey: ['reader-name'],
59 queryFn: () => getReaderName(),
60})
61```
62β
63The route awaits the query for content that must appear in the initial HTML:
64β
65```tsx title="src/routes/preferences.tsx"
66import { useSuspenseQuery } from '@tanstack/react-query'
67import { createFileRoute } from '@tanstack/react-router'
68import { readerNameOptions } from '../utils/preferences'
69β
70export const Route = createFileRoute('/preferences')({
71 loader: async ({ context }) => {
72 await context.queryClient.query(readerNameOptions)
73 },
74 headers: () => ({ 'Cache-Control': 'private, no-store' }),
75 component: Preferences,
76})
77β
78function Preferences() {
79 const { data: name } = useSuspenseQuery(readerNameOptions)
80 return <p>Hello, {name}</p>
81}
82```
83β
84Both calls use the same query key and options. The loader populates the request's cache; the component reads it; the integration transfers it to the browser. The component does not need to call the server function again in an effect.
85β
86For a parameterized resource, include its identity in the key, such as `['post', postId]`. If search values affect the result, validate them and include them in both `loaderDeps` and the query key. Keep secrets out of keys and serialized query data.
87β
88## Await critical data and stream secondary data
89β
90Await queries that determine the page's main content, title, authorization, redirects, or whether it exists. Return title and description data from the loader when a route's `head` needs them, as the example's post route does.
91β
92Secondary content can begin loading without blocking the loader, then render inside a Suspense boundary. Keep that query under the SSR integration so its result can stream to the browser. Handle the imperative query promise's rejection as well as the component's error boundary; a fire-and-forget promise should not become an unhandled server rejection.
93β
94The example's existing `/deferred` route shows a separate Suspense boundary. See [streaming and prefetching](/router/latest/docs/integrations/query#prefetching-and-streaming) for the integration's behavior. A plain `useQuery` that has no loader prefetch is not a guarantee that its data will be in the server-rendered HTML.
95β
96## Invalidate Query after a server mutation
97β
98The preference example validates the display name and writes its cookie inside a POST server function. Its `src/start.ts` enables Start's CSRF middleware for server-function requests. The component calls that function through `useServerFn`, then invalidates the query that reads the cookie:
99β
100```tsx
101const queryClient = useQueryClient()
102const save = useServerFn(saveReaderName)
103const mutation = useMutation({
104 mutationFn: (name: string) => save({ data: name }),
105 onSuccess: () =>
106 queryClient.invalidateQueries({ queryKey: readerNameOptions.queryKey }),
107})
108```
109β
110Returning the invalidation promise keeps the mutation pending until its active query's refetch finishes. The form can use `mutation.isPending` and `mutation.isError` for feedback. The example also disables its JavaScript-dependent form until hydration and uses a POST method so a native submission cannot put form values in the URL.
111β
112Invalidate the data's actual owner. `queryClient.invalidateQueries` refreshes Query data; `router.invalidate()` reloads Router-owned loader data and route context. Use both only when the mutation changes both, such as a login that changes root authentication context and private queries. Neither call purges your CDN or invalidates a database cache.
113β
114If a mutation returns the complete updated resource, `setQueryData` can update that cache entry directly instead. Optimistic updates need cancellation, rollback on failure, and reconciliation with the server result. This example uses a confirmed write followed by invalidation, not an optimistic update.
115β
116## Keep account data isolated beyond SSR
117β
118Request-scoped QueryClients prevent cross-request cache sharing on the server. They do not authorize reads or automatically clear a browser cache when its account changes.
119β
120For authenticated applications, authorize every private read and mutation on the server, including resource-level permissions. On sign-out or account switching, cancel and remove the previous account's private queries, then reload the relevant route context. Include account or tenant identity in keys when that is part of the resource's identity, but do not treat a key as an access-control check.
121β
122The `/preferences` route and its server functions return `Cache-Control: private, no-store` because their output varies by cookie. Verify the final response through your hosting provider and CDN. Do not publicly cache personalized HTML merely because the QueryClient itself is isolated.
123β
124## Diagnose extra requests
125β
126Check when and where each request occurs. A background refresh after the freshness window, a reconnect, or a deliberate invalidation can be expected.
127β
128| Symptom | Check |
129| --------------------------------------------------- | --------------------------------------------------------------------------------------------- |
130| A read repeats immediately after hydration | Query `staleTime`, hydration configuration, matching keys, and accidental extra QueryClients |
131| Navigation loads different data than a direct visit | Search validation, `loaderDeps`, query keys, and server-only boundaries |
132| A mutation succeeds but old data stays visible | Which cache owns the displayed value and which keys were invalidated |
133| A second account sees the first account's data | Module-scoped server clients, browser cache cleanup, account keys, and shared HTTP caches |
134| SSR contains only a loading state | Whether the loader awaited critical data and whether the component reads the prefetched query |
135β
136Start with the same options object in the loader and component. Avoid adding manual hydration code or disabling all refetching to hide a duplicate request.
137β
138## Run the example's checks
139β
140From the repository root, install dependencies and build the framework packages as described in [Contributing](https://github.com/TanStack/router/blob/main/CONTRIBUTING.md). Then:
141β
142```sh
143cd examples/react/start-basic-react-query
144pnpm exec playwright install chromium
145pnpm test:e2e
146pnpm build
147QUERY_EXAMPLE_PRODUCTION=1 pnpm test:e2e
148```
149β
150The tests send concurrent SSR requests with different preference cookies while using the same query key. Each HTML response must contain only its own reader's value. The browser test then requires zero additional reads during hydration, exactly one read after mutation invalidation, and no extra read after a reload hydrates fresh data.
151β
152The post and user demos use JSONPlaceholder. The preference tests run without that external API.