Prefetching with handles
On this page
Handles help you avoid request waterfalls. The loader, or server component, reads the URL once, starts every query the page needs, and passes each component a reference to its query as a prop.
- A handle is a query's key and input. It holds no data.
- The component reads the query from it, fully typed, without naming the procedure or repeating its input.
- The client reads exactly the query the server started. With plain
queryOptions, an input that differs by a typo misses the prefetch and fetches again, silently.
In short
Load the handles where the page starts, and read each one in a component, which never names the procedure or repeats its input:
import { useSuspenseQuery } from '@tanstack/react-query';
import { createFileRoute } from '@tanstack/react-router';
import {
ensureEntry,
fromHandle,
loadHandles,
} from '@trpc/tanstack-react-query/unstable-handles';
import { useTRPC } from '~/lib/trpc';
export const Route = createFileRoute('/posts/$id')({
loader: async ({ context: { trpc }, params }) => {
const [handles] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id: params.id }),
});
return handles;
},
component: PostPage,
});
function PostPage() {
const handles = Route.useLoaderData();
const trpc = useTRPC();
const postQuery = useSuspenseQuery(fromHandle(trpc, handles.post));
return <h1>{postQuery.data.title}</h1>;
}The page, a server component, loads the handles:
import { ensureEntry, loadHandles } from '@trpc/tanstack-react-query/unstable-handles';
import { HydrateClient, trpc } from '~/trpc/server';
import { Post } from './post';
export default async function PostPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params;
const [handles] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
});
return (
<HydrateClient>
<Post post={handles.post} />
</HydrateClient>
);
}A client component, in its own file, reads one:
'use client';
import { useSuspenseQuery } from '@tanstack/react-query';
import { fromHandle, type inferQueryHandle } from '@trpc/tanstack-react-query/unstable-handles';
import { useTRPC, type TRPC } from '~/trpc/client';
export function Post(props: { post: inferQueryHandle<TRPC['post']['byId']> }) {
const trpc = useTRPC();
const postQuery = useSuspenseQuery(fromHandle(trpc, props.post));
return <h1>{postQuery.data.title}</h1>;
}- The handle carries the procedure and its input, typed.
- The data reaches the browser's cache through TanStack Query's dehydrate and hydrate: see Frameworks.
- Mutations don't change. To refetch a handle's query after one, invalidate
{ queryKey: handle.queryKey, exact: true }.
Loading handles
loadHandles(trpc, entries) starts every entry, then resolves to [handles, data]:
import {
ensureEntry,
loadHandles,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
const [handles, data] = await loadHandles(trpc, {
// Waits for the post, unless the cache has it
post: ensureEntry(trpc.post.byId, { id }),
// Doesn't wait
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});
handles.post;data.post;// The comments may have no data yet, so they aren't on `data`
data.comments;- Building an entry starts nothing. The load starts every entry before it waits for any, so their order doesn't matter.
handleshas a handle for each entry. Return it from the loader, or pass it on as props.- In a client component, don't call
loadHandlesduring render: each render would start the entries again. Server components can. A client component that renders before anything loaded its query reads it withuseSuspenseQuery(trpc.x.queryOptions(input)).
Using the data in a loader
data has the data of the entries the load waited for. Use it for the page title, a redirect or a not-found check. Return handles, not data, so the data doesn't cross to the browser twice.
Waiting for some, streaming others
List every query in one load, whether the page waits for it or not. They all start together. A second load waits for everything the first one waited for, so use one only for dependent queries.
Each entry chooses whether the page waits for its query:
prefetchEntry | ensureEntry | fetchEntry | |
|---|---|---|---|
| Page waits for data | No | Yes | Yes |
In data | No | Yes | Yes |
| With stale data | Refetches in the background | Resolves at once, refetches in the background | Waits for the refetch |
| Reader's first render | Loading state, or cached data | The data | The data |
| When the request fails | The reader gets the error | The load rejects, unless it had cached data | The load rejects |
The page shows at once, with skeletons until the data comes in. Stale data shows at once and refetches.
Comments
No requests yet.
Load handles where the code can wait:
| Your app | Where | Proxy |
|---|---|---|
| TanStack Start, TanStack Router | Route loaders | The proxy in your router context |
| Next.js App Router | Server components | The server proxy from trpc/server.tsx |
| A SPA without loaders | Event handlers, such as a link's hover | useTRPC() |
Conditional queries
Put TanStack Query's skipToken in place of an entry to start nothing for it. Here, a post page loads its comments only when the URL opens the comments tab, /posts/1?tab=comments:
import { skipToken } from '@tanstack/react-query';
import {
ensureEntry,
loadHandles,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
import { z } from 'zod';
export const postRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/posts/$id',
validateSearch: z.object({
tab: z.enum(['post', 'comments']).default('post'),
}),
loaderDeps: ({ search }) => ({ tab: search.tab }),
loader: async ({ context: { trpc }, params: { id }, deps }) => {
const [handles] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments:
deps.tab === 'comments'
? prefetchInfiniteEntry(trpc.post.comments, { postId: id })
: skipToken,
});
handles.comments; return handles;
},
});- Its handle is
undefined, so render the reader only when there's a handle:{handles.comments && <Comments comments={handles.comments} />}. - It has no key in
handles,dataorloadHandlesSettled's results, so the handles still serialize as Next.js props. - Take the condition from what the loader knows: the URL, as here, the session, or another load's data. See Start every query from the URL and Dependent queries.
TanStack Query equivalents
Each entry is one TanStack Query call:
| tRPC | TanStack Query |
|---|---|
prefetchEntry(trpc.x, input, opts) | void queryClient.prefetchQuery(trpc.x.queryOptions(input, opts)) |
ensureEntry(trpc.x, input, opts) | await queryClient.ensureQueryData({ ...trpc.x.queryOptions(input, opts), revalidateIfStale: true }) |
fetchEntry(trpc.x, input, opts) | await queryClient.fetchQuery(trpc.x.queryOptions(input, opts)) |
prefetchInfiniteEntry, ensureInfiniteEntry, fetchInfiniteEntry | prefetchInfiniteQuery, ensureInfiniteQueryData (with revalidateIfStale: true), fetchInfiniteQuery |
fromHandle(trpc, handle, opts) | trpc.x.queryOptions(handle.input, opts), with x taken from the handle |
The queryClient is the one the proxy was created with. The entry names follow the TanStack Query method each one calls.
Options:
inputis optional when the procedure's is:prefetchEntry(trpc.viewer).optstakesstaleTime,gcTime,retry,retryDelay,metaandtrpcrequest options. They apply to the load's request; readers use the options passed tofromHandle.
prefetchEntry: don't wait
- The page renders at once, and the data streams in.
- The reader shows cached data, or suspends. Give it its own
<Suspense>, or the nearest boundary above shows its fallback, which may be the whole page. - It never makes the load reject. The reader gets the error: see Errors.
- Use it for slow queries, content below the fold and side panels.
ensureEntry: wait
- The load waits until the cache has data, so the reader renders it at once.
- With cached data, even stale, it resolves at once and refetches in the background.
- It rejects only if the cache had no data and the request fails.
- Use it for data the page can't render without, or needs before rendering.
fetchEntry: wait for fresh data
- Like
ensureEntry, but with stale data it waits for the refetch. - Use it when the loader reads the data and needs it fresh, such as for a redirect.
- In a browser loader, prefer
ensureEntry: a fetch entry holds up the navigation until the refetch is done. - TanStack Router shows a visited page with its last loader data while the loader reruns. To wait, set
defaultStaleReloadMode, or a loader'sstaleReloadMode, to'blocking'. - In server components, ensure and fetch behave the same: the request's
QueryClientstarts empty.
Start every query from the URL
A loader runs before anything renders, and all it has is the URL: params, search params and, on the server, the session. If every input comes from those, every request starts with the navigation.
- Path params name the thing:
/posts/$slug. - Search params hold filters, sort and page. Keep them out of component state: a loader can't see it, the back button doesn't restore it, and a shared link loses it.
- Typesafe APIs without codegen▲ 3
- Streaming responses over HTTP▲ 40
- Subscriptions with server-sent events▲ 27
What the loader sees
loaderDeps: ({ search }) => search,
// { sort: 'new', page: 1 }
loader: ({ deps }) =>
loadHandles(trpc, {
posts: prefetchEntry(trpc.post.list, deps),
}),Requests
- loaderpost.list({ sort: 'new', page: 1 })done
With handles, they all start together. Without, each starts once the component above it renders:
With handles Without
|-> post.byId |-> post.byId
|-> post.comments |-> post.comments
|-> post.byAuthor |-> post.byAuthor
The route loader starts every query from the URL: the article's id, or the list's page. One round trip.
Comments
No requests yet.
If the URL isn't enough, reshape the procedure
A procedure that takes an id from another query forces a waterfall on every page that calls it. Fix the procedure, not the page:
- Take what the URL has. Accept the slug and look up the id on the server.
- Return the joined data. Return the post with its author, not an author id.
The server sits next to the database, so the lookup costs a query there, not a round trip from the browser.
Before: the comments and the author need ids that only the post has.
async function loader(params: { slug: string }) {
const [first, { post }] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.bySlug, { slug: params.slug }),
});
// Nothing below can start until the post has arrived
const [second] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, {
postId: post.id,
}),
author: prefetchEntry(trpc.author.byId, { id: post.authorId }),
});
return { ...first, ...second };
}post.bySlug |-------|
post.comments |-------|
author.byId |-------|
After: post.comments takes the slug, and post.bySlug returns the author:
import { z } from 'zod';
import { db } from './db';
import { t } from './trpc';
export const appRouter = t.router({
post: t.router({
bySlug: t.procedure
.input(z.object({ slug: z.string() }))
.query(async ({ input }) => {
const post = await db.post.bySlug(input.slug);
return { ...post, author: await db.author.byId(post.authorId) };
}),
comments: t.procedure
.input(
z.object({ slug: z.string(), cursor: z.number().nullish() }),
)
.query(async ({ input }) => {
const post = await db.post.bySlug(input.slug);
return db.comment.list({
postId: post.id,
cursor: input.cursor ?? null,
});
}),
}),
});async function loader(params: { slug: string }) {
// Both start from the URL, together
const [handles] = await loadHandles(trpc, {
comments: prefetchInfiniteEntry(trpc.post.comments, {
slug: params.slug,
}),
post: ensureEntry(trpc.post.bySlug, { slug: params.slug }),
});
return handles;
}post.bySlug |-------|
post.comments |-------|
Reading a handle
fromHandle(trpc, handle, opts?) returns trpc.<path>.queryOptions(handle.input, opts), or infiniteQueryOptions for an infinite handle. Pass it to any TanStack Query hook:
const trpc = useTRPC();
const postQuery = useSuspenseQuery(fromHandle(trpc, props.post));
const titleQuery = useQuery(fromHandle(trpc, props.post, { select: (post) => post.title }));
const [aQuery, bQuery] = useSuspenseQueries({
queries: [fromHandle(trpc, props.a), fromHandle(trpc, props.b)],
});- Only
loadHandlesmakes handles. A hand-written object doesn't type-check, andfromHandlethrows on it. handle.inputis the typed input. An infinite handle's leaves outcursoranddirection.- Reads share cache entries with
trpc.<path>.queryOptions(input). handle.queryKeycarries no data type, so the handle stays serializable. For a typed key, usefromHandle(trpc, handle).queryKeyortrpc.post.byId.queryKey(handle.input).
Typing props
Type props with inferQueryHandle<TRPC['post']['byId']>, or inferInfiniteQueryHandle for an infinite handle. Export type TRPC = TRPCOptionsProxy<AppRouter> from trpc/client.tsx once.
Reading with useQuery
With useQuery, no Suspense boundary is needed:
- It renders
status: 'pending'until the data arrives, and'success'at once after an ensure or fetch entry. - With server rendering, read a prefetch entry's handle with
useSuspenseQuery. Otherwise the server can render the loading state while the browser has the data, a hydration mismatch (TanStack/query#9399).
To change the input in the component, for a search term the URL can't hold, call the procedure and start from the handle's input:
const [term, setTerm] = useState(props.comments.input.term);
const commentsQuery = useSuspenseInfiniteQuery(
trpc.post.comments.infiniteQueryOptions(
{ ...props.comments.input, term: useDeferredValue(term) },
{ getNextPageParam: (last) => last.nextCursor },
),
);- While the input matches the handle's, it reads the loader's cache entry.
- Render
<Comments key={postId} … />, so a new post resets the term. - For sort and filters, use a search param instead.
When the cache loses the data
A handle carries no data, and the cache can lose it even after an ensure entry:
resetQueries()clears it and refetches at once.removeQueries()andclear(), such as on logout, drop it. The reader loads it again when it next renders.- After
gcTimeunused, TanStack Query drops it. invalidateQueries()keeps it and refetches in the background, so nothing shows a loading state.
So give every reader a loading state: a Suspense boundary, or a 'pending' case.
Infinite queries
For procedures with a cursor input, use prefetchInfiniteEntry, ensureInfiniteEntry and fetchInfiniteEntry. They load one page, or more with pages:
const [handles, data] = await loadHandles(trpc, {
comments: ensureInfiniteEntry(
trpc.post.comments,
{ postId: id, limit: 20 },
{ pages: 3, getNextPageParam: (last) => last.nextCursor },
),
});
data.comments.pages;-
pagesis how many pages the load fetches, also when it refetches stale pages: the cache then keeps only that many. To refetch every page the reader loaded, leave it out. -
Functions can't cross to the client, so pass
getNextPageParamagain when you read:fromHandle(trpc, props.comments, { getNextPageParam: (last) => last.nextCursor }) -
Also pass it to entries in loaders that run in the browser. Refetching stale pages needs it from page two on.
-
Type props with
inferInfiniteQueryHandle.
Dependent queries
A query whose input comes from another query's result is a waterfall. Each step costs a round trip. First try to reshape the procedure. If you can't, there are two ways, and both pay the round trip.
In a loader
Load the first query, then build the second load from its data:
const [first, { post }] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});
const [second] = await loadHandles(trpc, {
moreByAuthor: prefetchInfiniteEntry(trpc.post.byAuthor, {
authorId: post.authorId,
}),
});
const handles = { ...first, ...second };In a component
Read it in the component that gets the input:
const postsQuery = useSuspenseInfiniteQuery(
trpc.post.byAuthor.infiniteQueryOptions(
{ authorId },
{ getNextPageParam: (last) => last.nextCursor },
),
);- In TanStack Router,
beforeLoadcan wait for the first query before the loader runs: see TanStack Start.
Frameworks
Each framework loads the handles where the page starts and passes them to the components that read them. Set tRPC up with the framework's guide first.
On a page
After the TanStack Start setup, the route's loader loads the handles and its component passes them on:
import { createFileRoute } from '@tanstack/react-router';
import {
ensureEntry,
loadHandles,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
import { Suspense } from 'react';
import { Comments } from '~/components/comments';
import { Post } from '~/components/post';
export const Route = createFileRoute('/posts/$id')({
loader: async ({ context: { trpc }, params }) => {
const [handles] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id: params.id }),
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: params.id }),
});
return handles;
},
component: PostPage,
});
function PostPage() {
const handles = Route.useLoaderData();
return (
<>
<Post post={handles.post} />
<Suspense fallback={<p>Loading comments…</p>}>
<Comments comments={handles.comments} />
</Suspense>
</>
);
}On a page
After the Next.js App Router setup, export HydrateClient = unstable_createHydrateClient(getQueryClient) from trpc/server.tsx. The page, a server component, loads the handles and passes them to client components:
import {
ensureEntry,
loadHandles,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
import { Suspense } from 'react';
import { HydrateClient, trpc } from '~/trpc/server';
import { Comments } from './comments';
import { Post } from './post';
export default async function PostPage(props: { params: Promise<{ id: string }> }) {
const { id } = await props.params;
const [handles] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});
return (
<HydrateClient>
<Post post={handles.post} />
<Suspense fallback={<p>Loading comments…</p>}>
<Comments comments={handles.comments} />
</Suspense>
</HydrateClient>
);
}'use client';
import { useSuspenseQuery } from '@tanstack/react-query';
import { fromHandle, type inferQueryHandle } from '@trpc/tanstack-react-query/unstable-handles';
import { useTRPC, type TRPC } from '~/trpc/client';
export function Post(props: { post: inferQueryHandle<TRPC['post']['byId']> }) {
const trpc = useTRPC();
const postQuery = useSuspenseQuery(fromHandle(trpc, props.post));
return <h1>{postQuery.data.title}</h1>;
}HydrateClient
- It sends the request's queries to the browser, pending ones too, which stream in as they settle.
- It sends each query once per request, so a nested server component can load more handles and render its own. A query is sent again only when the server has newer data.
- It works only in server components, and for
queryClient.prefetchQuerytoo. - Handle inputs cross through React's serialization, not your transformer. Keep them to JSON values and
Dates. - For a 404, use an ensure entry and call
notFound(): see Errors.
Metadata, static and ISR pages
generateMetadatagets the page's query client. Fetch there, and the page's ensure entry reuses the data.- A page whose tRPC context reads
headers()renders on every request.loadHandleslets Next.js see that, so the build marks the page dynamic. - To prerender the page and revalidate it, load it with a proxy whose context reads no request data,
trpcStaticfrom Static and ISR pages:
import { ensureEntry, loadHandles } from '@trpc/tanstack-react-query/unstable-handles';
import { getQueryClient, HydrateClient, trpcStatic } from '~/trpc/server';
import { Post } from './post';
type Props = { params: Promise<{ id: string }> };
export const revalidate = 60;
export function generateStaticParams() {
return [{ id: '1' }];
}
export async function generateMetadata(props: Props) {
const { id } = await props.params;
const post = await getQueryClient().fetchQuery(
trpcStatic.post.byId.queryOptions({ id }),
);
return { title: post.title };
}
export default async function PostPage(props: Props) {
const { id } = await props.params;
const [handles] = await loadHandles(trpcStatic, {
post: ensureEntry(trpcStatic.post.byId, { id }),
});
return (
<HydrateClient>
<Post post={handles.post} />
</HydrateClient>
);
}Errors
With ensure and fetch entries
When an entry the load waits for fails, loadHandles rejects with a TRPCEntryError. isTRPCEntryError(error, trpc.post.byId) checks which procedure failed and types error.cause:
import {
ensureEntry,
ensureInfiniteEntry,
isTRPCEntryError,
loadHandles,
} from '@trpc/tanstack-react-query/unstable-handles';
async function loader(id: string) {
const [handles] = await loadHandles(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments: ensureInfiniteEntry(trpc.post.comments, { postId: id }),
}).catch((error: unknown) => {
if (isTRPCEntryError(error, trpc.post.byId) && error.code === 'NOT_FOUND') {
notFound();
}
if (isTRPCEntryError(error, trpc.post.comments)) {
reportError(error.cause); }
throw error;
});
return handles;
}error.keyis the entry's key,error.paththe procedure,error.codethe tRPC code.- The load rejects on the first failure, without waiting for the others.
- An error with a
digest, such as the one Next.js'sheaders()throws in a static render, is rethrown as it is, also byloadHandlesSettled, so Next.js still sees it. A procedure's errors arrive as aTRPCError, as withfetchQuery.
Errors as values
loadHandlesSettled never rejects for a failed entry. It returns each waited-for entry's result as a value:
import {
ensureEntry,
loadHandlesSettled,
prefetchInfiniteEntry,
} from '@trpc/tanstack-react-query/unstable-handles';
const [handles, results] = await loadHandlesSettled(trpc, {
post: ensureEntry(trpc.post.byId, { id }),
comments: prefetchInfiniteEntry(trpc.post.comments, { postId: id }),
});
if (results.post.status === 'error') {
if (results.post.error.code === 'NOT_FOUND') {
notFound();
}
throw results.post.error;
}
results.post.data.title;With prefetch entries
A prefetch entry never makes the load reject. The reader gets the query's own error: useQuery returns status: 'error', and useSuspenseQuery throws to the nearest error boundary, unless the cache has data to keep showing. To report these in one place, use your QueryCache's onError.
Invalidation
Handles use normal tRPC query keys. Pass any of these to invalidateQueries:
{ queryKey: handle.queryKey, exact: true }: the handle's own query. Withoutexact, it also matches inputs that extend the handle's.trpc.post.pathFilter(): every query underpost.trpc.post.byId.queryFilter(input), orinfiniteQueryFilterfor an infinite handle.
To update data in place, use queryClient.setQueryData(trpc.post.byId.queryKey(handle.input), …).
Hydrated data keeps the server's fetch time. Set a staleTime above 0, as the setup guides do, or the client refetches right after hydration.
Testing
Load handles over a test QueryClient, seeded with fixture data:
import { QueryClient } from '@tanstack/react-query';
import { createTRPCOptionsProxy } from '@trpc/tanstack-react-query';
import { loadHandles, prefetchEntry } from '@trpc/tanstack-react-query/unstable-handles';
import { appRouter } from './router';
const queryClient = new QueryClient({
defaultOptions: { queries: { staleTime: Infinity, retry: false } },
});
const trpc = createTRPCOptionsProxy({ router: appRouter, ctx: {}, queryClient });
queryClient.setQueryData(trpc.post.byId.queryKey({ id: '1' }), {
id: '1',
title: 'Hello',
});
const [{ post }] = await loadHandles(trpc, {
post: prefetchEntry(trpc.post.byId, { id: '1' }),
});- Render the component under
QueryClientProviderandTRPCProviderwith the samequeryClient. - Leave out
setQueryDatato run the real procedure.
FAQ
Are handles safe to send to the browser?
Yes. A handle names a query the browser could call anyway, and every refetch runs validation and auth on the server again.
A handle does carry its input to the browser, as hydrated query keys already do. Only use inputs you'd show the client.
Where don't handles work?
- Server functions and server actions: their
QueryClientnever hydrates the page, so return data instead. - Outside hydration: a reader rendered on the server outside
HydrateClientorHydrationBoundaryfetches its query again. In development, tRPC warns once per query. - URLs and storage: a handle there gains nothing over its input.
Why functions, not methods on trpc?
Methods on trpc return plain TanStack Query options. Handles are helpers on top, and apps that don't use them don't load their code.
Why one load call, not one per query?
So a loader can't make a waterfall by the order of its lines.