Caching prefetched data in a server component
I have some prefetch queries in some of my Next.js server components. I have done this according to docs in "Advanced server rendering".
I used regular useQuery in client-side with the same query keys and query function. Everything worked fine except the caching part.
When I navigate somewhere and navigate back to my page which prefetches this query it seems to trigger my fetch function (getStatusKpi) every single time I navigate.
I guess it makes sense cuz the
queryClient is created per request. But I have no idea how to still get it cached. It might be Next.js related question, not tanstack query but I need help. Thanks in advance.1 Reply
genetic-orange•2mo ago
yes, it's a nextJs question, because you need to cache the server component or request or whatever.
if the server function "executes", the
prefetchQuery will run because there is no caching of that on the server.
theoretically you can take the content of the queryClient, cache it on the server in something like redis and re-store it from there, but really, you should be caching the server component itself with however nextJs allows you to do that (which really I have no idea because it changes frequently and there are like 4 different layers of caches 🤷♂️ )