vercel / next.js

The React Framework
https://nextjs.org
MIT License
122.63k stars 26.25k forks source link

`fetch` does not work when using manual suspense #67285

Open pedroalmeida415 opened 2 days ago

pedroalmeida415 commented 2 days ago

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 commented 2 days ago

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 commented 2 days ago

Accidentaly pressed the hotkey to comment and close, my bad

panukettu commented 2 days ago

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

jxdp commented 1 day ago

@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