Skip to main content
TanStack Query supports server-side rendering (SSR) through dehydration and hydration. This allows you to prefetch data on the server and seamlessly transfer it to the client.

Core Concepts

Dehydration

Dehydrate converts the QueryClient state to a serializable format on the server:

Hydration

Hydrate restores the dehydrated state on the client:

Next.js App Router

Server Component (Prefetching)

Client Component (Consuming)

Root Layout Setup

Set a staleTime in SSR apps to prevent immediate refetching on the client. The prefetched data is usually fresh enough for initial render.

Next.js Pages Router

_app.tsx Setup

Remix

Dehydrate Options

Customize what gets dehydrated:

Custom Dehydration Rules

Hydrate Options

Customize hydration on the client:

Streaming with Suspense

Next.js App Router supports streaming with React Server Components:

Handling Errors in SSR

Queries will not refetch on mount if they have fresh data from SSR. Set staleTime: 0 if you need immediate refetching, but this defeats the purpose of SSR.

Prefetching Multiple Queries

Prefetching Infinite Queries

Common Pitfalls

1. Not Setting staleTime

2. Creating QueryClient Inside Component

3. Query Key Mismatch

Testing SSR

Next Steps