Skip to content
Source
Sign inSign up
TanStack/query

Next.js cacheComponents (dynamicIO) dehydration error #9457

Send to my agent
Closedpluscubed(GitHub profile, opens in a new tab) opened this issue 10 comments

Describe the bug

In Next.js 15 with cacheComponents (formerly dynamicIO) turned on, dehydration causes an error:

Error: Route "/" used `Date.now()` instead of using `performance` or without explicitly calling `await connection()` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time
    at Home (app/page.tsx:15:42)
    at Home (<anonymous>)
  13 |     <main>
  14 |       <h1>Pokemon Info</h1>
> 15 |       <HydrationBoundary state={dehydrate(queryClient)}>
     |                                          ^
  16 |         <PokemonInfo />
  17 |       </HydrationBoundary>
  18 |     </main>

I think it's this Date.now() usage here:

https://github.com/TanStack/query/blob/3bcaa417ac302a93d17c4287d518121bb77d1b26/packages/query-core/src/hydration.ts#L82

I believe this issue is similar to #8277.

Your minimal, reproducible example

https://codesandbox.io/p/devbox/blazing-moon-kyqpg5

Steps to reproduce

I took the example at https://tanstack.com/query/latest/docs/framework/react/examples/nextjs-app-prefetching, changed to Next.js canary and enabled cacheComponents

Expected behavior

No error

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

All platforms

Tanstack Query adapter

react-query

TanStack Query version

5.83.0

TypeScript version

No response

Additional context

No response

  1. With cacheComponents/dynamicIO we need to choose whether the server component kicking off the prefetching is dynamic or static.

    If we want it to be dynamic (i.e. we do the prefetching every time the page renders on the server at runtime, rather than once at build time) then it works fine if we

    1. add await connection() to Home, to force it to render dynamically. (NB: this isn't necessary if we're already calling dynamic APIs such as headers() or cookies(), or we await the prefetch)
    2. wrap Home in a suspense boundary (or add loading.tsx)
    export default function Page() {
      return (
        <Suspense fallback="suspense fallback">
          <Home />
        </Suspense>
      );
    }
    async function Home() {
      await connection();
      const queryClient = getQueryClient();
    
      void queryClient.prefetchQuery(pokemonOptions);
    
      return (
        <main>
          <h1>Pokemon Info</h1>
          <HydrationBoundary state={dehydrate(queryClient)}>
            <PokemonInfo />
          </HydrationBoundary>
        </main>
      );
    }
  2. Trying to get it to work statically (i.e. prefetching and prerendering once at build time) by adding 'use cache' is problematic though. Depending how I do it, either

    1. I await the prefetching, and get an error about calling Date.now() (not allowed by next if we're trying to prerender a client component) when useBaseQuery calls new Observer()
      • I'm not sure exactly where the call to Date.now() is, but I imagine we'd have the same problem with HydrationBoundary
    2. I wrap PokemonInfo in suspense boundary - but then it bails out of server rendering
    3. I don't await the prefetching (and continue to use useSuspenseQuery) then there's a strange error telling me to add a suspense boundary or use cache - even though I already have use cache

    That said, I'm not sure if this is a use case react-query needs to support? I'm struggling to imagine when I'd want to fetch and render something on the server at build time, then update from the client.

    If the static case doesn't need addressing, I'd be happy to make a PR to update the example.


    Full error message 1:

    Error: Route "/" used `Date.now()` inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client
        at useBaseQuery.useState (../../src/useBaseQuery.ts:86:7)
        at useBaseQuery (../../src/useBaseQuery.ts:84:28)
        at useSuspenseQuery (../../src/useSuspenseQuery.ts:23:22)
        at PokemonInfo (app/pokemon-info.tsx:8:36)
      84 |   const [observer] = React.useState(
      85 |     () =>
    > 86 |       new Observer<TQueryFnData, TError, TData, TQueryData, TQueryKey>(
         |       ^
      87 |         client,
      88 |         defaultedOptions,
      89 |       ),

    full error message 3

    Error: Route "/": A component accessed data, headers, params, searchParams, or a short-lived cache without a Suspense boundary nor a "use cache" above it. See more info: https://nextjs.org/docs/messages/next-prerender-missing-suspense
  3. Thanks for the detailed analysis, the breakdown makes the issue clearer.

    I'd like it to get the benefits of Next.js's Partial Pre-Rendering (cacheComponents) - chiefly, rendering a static app shell (CDN'd) & streaming in dynamic content below Suspense boundaries.

    I want to use React Query for its client-side features (e.g. interval, refetchOnMount, infinite queries, etc), but still take advantage of the PPR first load.

    #8277 looks like the same symptom as this issue, but a different cause, which was fixed. A new Date.now() call was added later I think.

    An alternative I considered was populating initialData, by passing down a fetchQuery Promise into a client component that calls use(). But if I understand correctly, it would have the same drawbacks as listed here?https://tanstack.com/query/latest/docs/framework/react/guides/ssr#get-started-fast-with-initialdata

  4. Hm I suppose my use-case would fall under the dynamic case (do the prefetching every time the page renders on the server at runtime, rather than once at build time).

    The workaround solution would be to push await connection() / HydrationBoundary deeper into the component tree (and probably add multiple HydrationBoundarys). But that's a little annoying, and I don't quite understand why the hydration boundary dehydrate() call needs to be dynamic - am I missing something here?

  5. yeah I've been working through the exact same things - and finding all the wrong ways to do them :-)

    Sounds like making the component doing the prefetching dynamic would work for you. Then you can prerender the static shell (which doesn't include the data) and upload to CDN. At run time the static shell will be returned immediately, while the server will fetch fresh data and stream it to the client as part of the same client-server round trip.

    One gotcha which I found though: you probably want react-query to 'take over' after that, so when you return to the page 30 seconds later, you see data the from the react-query cache (with an optional background refetch)

    But as far as nextjs is concerned the page is dynamic, so by default every time you click the link a request is made to the server for next to rerender the page. In the meantime the user sees the suspense fallback or loading page. For me that defeats the whole point of using react-query.

    Seems the current solution to that is to set prefetch=true on the link (possibly on hover) so that nextjs caches the whole page in its client side router cache, by default for 5 minutes. So for 5 minutes we don't go back to the server for the page (unless we call revalidateTag/Path or router.refresh()); react-query is in charge of refetching specifc data as needed.

    (Or if you're not using dynamicIO/cacheComponents you can alter experimental.staleTimes.dynamic to be non-zero, so that nextjs caches non-prefetched dynamic pages once visited. But with the new settings it seems that only prefetched pages get put in the router cache so that doesn't work. Looks like in future we'll be able to use use cache: private but it might be a while before it's ready)

  6. TkDodocommented

    I think it's this Date.now() usage here:

    https://github.com/TanStack/query/blob/3bcaa417ac302a93d17c4287d518121bb77d1b26/packages/query-core/src/hydration.ts#L82

    I think / hope that’s not the problematic one because dehydrateQuery only happens on the server, and per the nextJs docs, the problem is that “A Client Component is accessing the current time with Date.now(), Date(), or new Date()”.

    The stack trace that points to new Observer is more likely because when we set the options in the constructor, we also create the initial observer result and there are some places where we call Date.now() as fallback .

    It could be this one if you’re using initialData ?

    https://github.com/TanStack/query/blob/fa4867377633f099b92440c2b7a94956b2f25c2b/packages/query-core/src/query.ts#L710

  7. The error in my OP is this one: "Cannot infer intended usage of current time with Date.now(), Date(), or new Date() in a Server Component". (It's the same error as #8277.)

    The new Observer error that @mdj-uk got is with 'use cache' and awaited prefetching. “A Client Component is accessing the current time with Date.now(), Date(), or new Date()”. That's a separate semi-related issue I think.

  8. That's right - sorry if I've confused things by mentioning the errors when you add 'use cache'. Can make a separate issue if that's helpful.

  9. In case it's helpful, I ran the original example from @pluscubed (without 'use cache') with nextjs server debugging. (https://codesandbox.io/p/devbox/quirky-clarke-5984kg?workspaceId=ws_NWeM56rFTtP8bj8JxvwSss)

    Debug stack trace points to dehydrateQuery():

    Error: Route "/" used `Date.now()` instead of using `performance` or without explicitly calling `await connection()` beforehand. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time
        at io (/project/workspace/node_modules/.pnpm/next@15.4.2-canary.8_react-dom@19.1.0_react@19.1.0/node_modules/next/dist/server/node-environment-extensions/utils.js:46:146)
        at now (/project/workspace/node_modules/.pnpm/next@15.4.2-canary.8_react-dom@19.1.0_react@19.1.0/node_modules/next/dist/server/node-environment-extensions/date.js:19:27)
        at dehydrateQuery (webpack-internal:///(rsc)/./node_modules/.pnpm/@tanstack+query-core@5.83.0/node_modules/@tanstack/query-core/build/modern/hydration.js:24:24)
        at eval (webpack-internal:///(rsc)/./node_modules/.pnpm/@tanstack+query-core@5.83.0/node_modules/@tanstack/query-core/build/modern/hydration.js:67:38)
        at Array.flatMap (<anonymous>)
        at dehydrate (webpack-internal:///(rsc)/./node_modules/.pnpm/@tanstack+query-core@5.83.0/node_modules/@tanstack/query-core/build/modern/hydration.js:66:51)
        at Home (webpack-internal:///(rsc)/./app/page.tsx:33:88)
        at Home (<anonymous>) {stack: 'Error: Route "/" used `Date.now()` instead of…app/page.tsx:33:88)
        at Home (<anonymous>)', message: 'Route "/" used `Date.now()` instead of using…rg/docs/messages/next-prerender-current-time', __NEXT_ERROR_CODE: 'E394'}

    Though my understanding is that this isn't a problem, it just forces us to make an explicit choice between static vs dynamic rendering, which we have to do anyway.

    In the 'use cache' case the culprit is https://github.com/TanStack/query/blob/234f2f4c6560c9555bb3aa04279040449e4becca/packages/query-core/src/utils.ts#L97 called by Query.isStaleByTime(). More details in https://github.com/TanStack/query/issues/9499

  10. TkDodocommented

    okay looking at the OP error:

    I think it’s clear that users either need to ”use cache” to capture the time of server-side-rendering at build time, or await connection() to opt into dynamic capturing.

    We need to send dehydratedAt: Date.now() from the server to the client to know when data was created on the server.

    Unless I’m missing something, all of this is intentional and I’m therefore closing this issue. Will have another look at #9499 because it seems different.

  11. TkDodo closed this

  12. TkDodo added labelsworks as designed

Sign in to join this conversation.