next.js icon indicating copy to clipboard operation
next.js copied to clipboard

`fetch` does not work when using manual suspense

Open pedroalmeida415 opened this issue 1 year ago • 4 comments

Link to the code that reproduces this issue

https://stackblitz.com/edit/stackblitz-starters-zpfjcc?file=app%2Fpage.tsx

To Reproduce

Enter demo and check terminal/console

Current vs. Expected behavior

I'm suspending a client component in order to fetch data necessary to render the component, but inside the callback, the window object is not defined, even though at this stage it should very much have access to it.

Removing window.location.origin will lead to another error: TypeError: Failed to parse URL from /multipliers.bin which I believe is because it doesn't have access to the window object in the first place, much like trying to do new URL('/multipliers.bin')

The library being used to suspend (suspend-react) has nothing to do with the problem, I tested without it by manually throwing a Promise and it still happens, kept it in for better code readability.

The versions of Next/React being used in the demo are not the latest ones because I couldn't get them to work on stackblitz, but I did try locally with the latest releases and the error still persists

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP Fri Mar 29 23:14:13 UTC 2024
  Available memory (MB): 7947
  Available CPU cores: 8
Binaries:
  Node: 20.8.1
  npm: 10.1.0
  Yarn: 1.22.19
  pnpm: N/A
Relevant Packages:
  next: 14.2.4 // Latest available version is detected (14.2.4).
  eslint-config-next: 14.2.4
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 5.4.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Pages Router

Which stage(s) are affected? (Select all that apply)

next dev (local), next build (local)

Additional context

When running build, next throws Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error. It seems like it is trying to pre render a client component but I have no idea why.

pedroalmeida415 avatar Jun 28 '24 20:06 pedroalmeida415

It seems like Next.js really doesn't like that I use the suspense feature manually on a Client Page route, and it runs the request in a server environment even though it's not

Considering the following route structure, where both Page and Home are client components:

// app/page.tsx
<Suspense fallback={<div'>loading...</div>}>
  <Home />
</Suspense>

Inside <Home /> I'm fetching data that will be used to display the contents of the page (it can't be a server component)

The fecthing goes like this:

// suspend() is using suspend-react library - I also tried without it (just throwing a Promise and managing state manually)
// AND with react-query, both yield the same error
async function getMultipliers() {
      const res = await fetch(`/multipliers.bin`)
      const buffer = await res.arrayBuffer()
      const decompressedStreamBuffer = LZMA.decompressFile(buffer)
      const rawBytes: Uint8Array = decompressedStreamBuffer.toUint8Array()

      return rawBytes
}

const multipliersArray = suspend(async () => await getMultipliers(), [])

This correctly suspends the component and displays the fallback in the <Suspense /> tag, but I get an error in the console:

react-dom.development.js:17497 Uncaught 
Error: Failed to parse URL from /positions.bin
    at updateDehydratedSuspenseComponent (react-dom.development.js:17497:1)
    at updateSuspenseComponent (react-dom.development.js:17193:1)
    at beginWork$1 (react-dom.development.js:18509:1)
    at beginWork (react-dom.development.js:26927:1)
    at performUnitOfWork (react-dom.development.js:25748:1)
    at workLoopSync (react-dom.development.js:25464:1)
    at renderRootSync (react-dom.development.js:25419:1)
    at performConcurrentWorkOnRoot (react-dom.development.js:24504:1)
    at workLoop (scheduler.development.js:256:1)
    at flushWork (scheduler.development.js:225:1)
    at MessagePort.performWorkUntilDeadline (scheduler.development.js:534:1)

Now, I managed to hack my way around this error by dinamycally importing the <Home /> component and explicitly setting the ssr to false in the options:

const Home = dynamic(() => import('@/components/home/home').then((mod) => mod.Home), {
  ssr: false,
  loading: () => <div>loading...</div>,
})

With this, the error goes away, but I'm left wondering why it even happened in the first case

This <Home /> component shouldn't even exist, it should just be the content of the app/page.tsx component, which combined with an app/loading.tsx component gives the exact structure needed to use suspense, so I'm convinced there's something wrong going on here

pedroalmeida415 avatar Jun 28 '24 20:06 pedroalmeida415

Accidentaly pressed the hotkey to comment and close, my bad

pedroalmeida415 avatar Jun 28 '24 20:06 pedroalmeida415

"use client" only means the code will be sent to the browser, it does not skip server rendering.

panukettu avatar Jun 29 '24 10:06 panukettu

@pedroalmeida415 "use client" does not mean "client only", it means "send all the JS to the client".

In a nutshell, you are trying to use the library as one would in a plain React application.

Try using useSuspenseQuery from react-query. You need to use hooks; if you only want to fetch in the browser, you would run the fetch inside useEffect and then suspend from there. Or you can save yourself a lot of effort and use react-query.

Or better yet, use a server component and let Next build your page statically: https://stackblitz.com/edit/stackblitz-starters-jcwjjf?file=app%2Fpage.tsx

ijxy avatar Jun 29 '24 17:06 ijxy

@pedroalmeida415 "use client" does not mean "client only", it means "send all the JS to the client".

In a nutshell, you are trying to use the library as one would in a plain React application.

Try using useSuspenseQuery from react-query. You need to use hooks; if you only want to fetch in the browser, you would run the fetch inside useEffect and then suspend from there. Or you can save yourself a lot of effort and use react-query.

Or better yet, use a server component and let Next build your page statically: https://stackblitz.com/edit/stackblitz-starters-jcwjjf?file=app%2Fpage.tsx

From the react docs. https://react.dev/reference/rsc/use-client#how-use-client-marks-client-code

During render, the framework will server-render the root component and continue through the render tree, opting-out of evaluating any code imported from client-marked code.

The server-rendered portion of the render tree is then sent to the client. The client, with its client code downloaded, then completes rendering the rest of the tree.

I am encountering this error when using the TRPC integration with react-query's useSuspenseQuery hook. Code marked with 'use client' shouldn't run on the server. The issue I am encountering with useSuspenseQuery could be different but it seems very similar to this issue.

rob-steele-active avatar May 06 '25 18:05 rob-steele-active