Server-side prefetching with TanStack Query in Next.js (App Router)
Hi all! I'm using Next.js App Router and integrating TanStack Query. I’ve set up server-side data fetching using prefetchQuery in server components and then hydrating the data into client components using <HydrationBoundary> and dehydrate. This works fine — my client component receives the data and doesn't re-fetch unnecessarily.
However, I’ve noticed something that I want to confirm:
When I navigate between pages (using <Link> in a shared layout header), the server component runs again, which triggers the prefetchQuery on the server. So, a GRPC network call is made even though the data is already in the cache on the client.
On the client side, the data is available immediately from hydration, and isRefetching remains false (until the stale time expires). This means no client re-fetch occurs because the data is fresh.
Is my understanding correct?
On each navigation, the server component re-renders and runs prefetchQuery, which triggers a network call (because server-side cache is per request).
On the client, since the data is already hydrated and not stale, it doesn't trigger a re-fetch — just uses the hydrated data.
Once the data becomes stale, isRefetching turns true and the client fetches the latest data.
Is this the expected behavior? I assume this is because the server doesn’t share the client’s cache, so it must re-fetch on each server-side navigation, even if the client already has the data.
Thanks in advance!
8 Replies
robust-apricot•7mo ago
Yep
metropolitan-bronzeOP•7mo ago
thank you, for clarifying my doubt
robust-apricot•7mo ago
Now awaiting the prefetch on the server can speed things up
Or caching the server component (however that works in next)
metropolitan-bronzeOP•7mo ago
i checked, but i couldnt find a clean way to cache the server component
robust-apricot•7mo ago
Did you try "use cache"?
judicial-coral•7mo ago
I have the same setup and was wondering if it's possible to avoid "revalidating" the server component on each <Link/> navigation?
More of a nextjs question but maybe someone here knows.
robust-apricot•7mo ago
the nextjs router cache should take care of this: https://nextjs.org/docs/app/deep-dive/caching#client-side-router-cache
Deep Dive: Caching | Next.js
An overview of caching mechanisms in Next.js.
robust-apricot•7mo ago
but again, nextJs caching is complicated 😅