Prefetching tRPC Queries on the Server
What you'll learn: How to prefetch tRPC queries during server-side rendering so data is already in the cache when your React app hydrates.
The Problem: Waterfalls and Loading States
When using tRPC queries in a client-side React app, users see loading spinners while data fetches. With server-side rendering (SSR) or static site generation (SSG), you can fetch data on the server and send fully-rendered HTML to the browser — but you still need to "hydrate" TanStack Query's cache so the client doesn't refetch unnecessarily.
The Solution: createServerSideHelpers
tRPC provides createServerSideHelpers to prefetch queries on the server. Think of it as a "preview pass" — the server runs your queries, populates TanStack Query's cache, then serializes that cache to send along with the HTML.
How it works:
- Server-side: Call
createServerSideHelperswith your tRPC router and context - Fetch data: Use
helpers.users.getAll.prefetch()to run queries - Serialize cache: Call
helpers.dehydrate()to extract the cache state - Pass to client: Send the dehydrated state as props to your page component
- Client-side: Wrap your app with
<HydrationBoundary state={dehydratedState}>so TanStack Query rehydrates the cache
The magic: When your component first renders on the client, trpc.users.getAll.useQuery() finds the data already in cache — no loading state, no extra network request. The user sees instant content.
This pattern combines the SEO and performance benefits of SSR with the interactive benefits of client-side React, all while maintaining end-to-end type safety.
Key Takeaway: Use createServerSideHelpers to prefetch tRPC queries during SSR/SSG and hydrate TanStack Query's cache for instant, spinner-free data on first render.