sveltejs / kit

web development, streamlined
https://svelte.dev/docs/kit
MIT License
18.71k stars 1.94k forks source link

Data from load function is not persistent after rendering #12469

Closed J4gQBqqR closed 3 months ago

J4gQBqqR commented 3 months ago

Describe the bug

I am passing a random string through load function. I am expecting that the already generated string that I get from load function will be persistent during rendering my webpage. However, the rendered string and the one generated during SSR is different.

Reproduction

https://stackblitz.com/edit/vitejs-vite-4uijlv?file=my-app%2Fsrc%2Froutes%2F%2Bpage.svelte

cd my-app/
npm install
vite dev

Notice that the string printed in the console is different than the one showing in the webpage.

图片

Logs

No response

System Info

System:
    OS: Linux 5.0 undefined
    CPU: (2) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 0 Bytes / 0 Bytes
    Shell: 1.0 - /bin/jsh
  Binaries:
    Node: 18.20.3 - /usr/local/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 10.2.3 - /usr/local/bin/npm
    pnpm: 8.15.6 - /usr/local/bin/pnpm
  npmPackages:
    @sveltejs/adapter-auto: ^3.2.2 => 3.2.2 
    @sveltejs/kit: ^2.5.18 => 2.5.18 
    @sveltejs/vite-plugin-svelte: ^3 => 3.1.1 
    svelte: ^5.0.0-next.1 => 5.0.0-next.183 
    vite: ^5.3.3 => 5.3.3

Severity

blocking all usage of SvelteKit

Additional Information

I have the following questions:

  1. Am I using the load function in a wrong way?
  2. Why the load function seems to re-run itself during client side hydration and generates a different ID than the one I got during SSR?
  3. Am I understanding SSR and load function incorrectly? Is sveltekit hydration re-runing the load function on the client side regardless I run it already during SSR or not?

PS: I tried both svelte 4 and svelte 5, both are the same.

Conduitry commented 3 months ago

This is the intended behavior. https://kit.svelte.dev/docs/load#universal-vs-server Universal load functions run on both the client and the server. Among other reasons, this is so that they can return things that can't be serialized and sent over the network. In your case, this results in the app being hydrated on the client side to a different value than was rendered on the server.

J4gQBqqR commented 3 months ago

I guess I am misinterpreting what it means by running on "both" sides. I was under the impression that the client side code will not repeat whatever that is already generated from the server side so as to make the rendering faster. It might be too magical for client side to "hydrate" in that fashion.

It turns out that only the REST API fetch inside of the load function is not re-run.

The feature I was imaging could possibly be the sale point of the Qwik framework.