Skip to content
Source
Sign inSign up
TanStack/query

Nextjs Streaming+Server Action Error: Server Functions cannot be called during initial render. #6591

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

Describe the bug

image

Your minimal, reproducible example

codesandbox

Steps to reproduce

error output in terminal

How often does this bug happen?

Every time

Tanstack Query adapter

react-query 5.0.0 react-query-next-experimental

  1. suspense queries run on the server as well. This seems to be a nextjs design decision that you cannot call server actions during SSR. There isn't anything we can do here.

  2. TkDodo closed this

  3. TkDodo added labelswontfix

  4. TkDodo added labelsupstream

  5. Is there a good way to get around this? It feels like a really nice use case for useSuspenseQuery to be able to define a server action for data fetching and plug it in to React Query so that components can automatically suspend and get their data via these fancy RPC calls rather than having to wire up a fetch call + API route. Quite unfortunate that it doesn't seem to be able to work like this.

  6. Idk, please ask nextJs 😅

  7. @ajwootto, I experienced same issue which I resolved by reexporting my request functions in separete file containing "use server" and "server-only pragmas and added named export export * as queries from "./queries-server"; of queries-server.ts in index file to make importing more consistent across projects.. Then I added conditional to my queryFn function where I check for window to distinguish SSR and client Server Action. Screenshot 2024-05-14 at 12 40 13

    It does feels hacky but does its job for now. It imposes some additional complexities to the project since I couple tanstack query with jotai state management and leverage jotai-tanstack-query library in which I have to take care of atom hydration and such.

    I hope this discovery finds you well.

  8. @TkDodo I've encountered this issue following Advanced Server Rendering which kinda implicitly states that getPosts it's server action If that's not true I have concerns that sharing fetching logic between server and client is a good thing

  9. Calling the Server Action from an RSC works fine, so injecting initial data via useSuspenseQuery()'s initialData does the job and get rid of the errors, while keeping SSR ✅

    I'm not entirely sure what the initial "fetch waterfall" warning mean, so maybe there are some hidden costs I'm not seeing.

    (I know it's a Next thing, but this is the page I find from Google so I'm writing here for reference)

    Something like that:

    Parent Server Component

    function Parent() {
    	const data = await getData(); // server action
    	return <ChildClientComponent initialData={data} />
    }

    Child Client Component

    function Child({ initialData }: { initialData: Data }) {
    	const query = useSuspenseQuery({
    		queryKey: ['data'],
    		queryFn: () => getData(), // the very same server action
    		initialData,
    	});
    }
  10. even though I am seeing this error today on one screen, I feel like the rest of my app does work this way? I think some mixture of actions.ts files and the "use server" directive can get you around this

  11. In my case, I just needed to make sure I was awaiting the promise in the Page SRC - that cleared the error in the client component

  12. Works for me if i cache the result of the server method using unstable_cache: https://nextjs.org/docs/app/api-reference/functions/unstable_cache

  13. In my case, I just needed to make sure I was awaiting the promise in the Page SRC - that cleared the error in the client component

    Hello it didn't do anything for me :( Still looking for a good solution using useSuspenseQuery

  14. In case it helps anyone because i just went through turning on Cache Components in a medium-sized app:

    • If you have useSuspenseQuery() and it doesn't get initial data somehow, it will try to run its queryFn on initial render server-side and it complains if it's a Server Function (it feels to me that it should be able to sort that out? that's on Next.js); so you can either
      • Pass it initialData (like igor9silva showed) and no error
      • Use the prefetcher pattern (which i like) higher up, and make sure it has a connection() if necessary, e.g. i have:
    export async function Prefetcher({ children }: { children: React.ReactNode }) {
      await connection()
    
      const queryClient = getQueryClient()
      void queryClient.prefetchQuery(cartQueryOptions())
    
      return <HydrationBoundary state={dehydrate(queryClient)}>{children}</HydrationBoundary>
    }

    and this wraps children in some of my layout.tsx files (and you must have some <Suspense> wrapping it), and this also avoids the error.

Sign in to join this conversation.