You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You can't just blindly create a store in SSR or it'll end up being a global store shared by all users (#4339). We should provide a helper that ties it to the request.
Describe the proposed solution
At the very least we can make it part of the Svelte context. SvelteKit does this internally with its own stores.
I wonder if we couldn't make it available earlier. If we only make it part of the Svelte context then you can't use it in load. If we additionally tied it to the request it would be available throughout the rendering of the request.
There are a couple things we might make optional. E.g. we could potentially look for 'whatever' in locals automatically. Or we could make the request optional - if it's not provided the store would only be available in the template (at least on the server).
Alternatives considered
The user could create the store themselves if we just want it available in the template. That starts getting cumbersome if they want it available either as a singleton in the browser or tied to the request on the server. It's impossible if they want to populate it from locals
Some of the APIs I've proposed here may be open for debate on the actual details
Importance
would make my life easier
Additional Information
No response
Reacted by Tee Ming, Alex, Åukasz Polowczyk, kvetoslavnovak, themajashurka, Dirk Porsche, Libor VanÄk, Noah Dunbar, Mads, Maxime and 8 more
Great idea. Would it make sense to provide different options of how and when the store should be created and populated. Such as âonce on first page loadâ or âfor every page loadâ or
I Imagine this might be useful for the large amount of people who enjoy integrating client side stores with responsive backend functionality such as firebase authentication / snapshot listeners.
Not sure what it would look like though or if it makes sense, or if these types of behaviors would have to be solved by each developer.
The idea sounds good, I'm not fully sure on the details yet. I think this only makes sense in the context of the shared load function, so it runs on the server on first render and is updated within the client afterwards. So locals would be the shared thing on the server and this would be the shared thing in the shared load (basically the same split as with session previously). Also, is handle the best place for this? handle runs for every request, but this would only be available inside the shared load function. Something like getSession makes more sense to me.
Another thing I'm not sure about is if this should be reserved for stores only, or if you could place arbitrary things in there. You could place arbitrary things inside stores though, and having it a non-store only makes sense for things that never update, which shouldn't live inside this anyway - so, probably fine?
Instead of createStore(request, 'whatever', request.locals.whatever); I think it would make more sense to add or set a store to the request.
Something like:
A shared object across shared load functions would be amazing! (Maybe change the name to something else since itÂīs not only about session data?)
But creating stores would make things a bit complicated. Svelte stores are pretty useless on the server side, atleast i donÂīt get the benefit. We already have locals for server context, eventually something like session for shared context (like @dummdidumm suggested) and svelteÂīs context for ui context.
With $page.data we already have a store thatÂīs always in sync and keeps all data in one spot. I wonder why thatÂīs not sufficient?
Seems more like a doc thing making clear how stores work and how to safely use them with sveltekit.
What became clear to me that getSession was used for multiple things at once.
pass data from server to client load functions
make cross-cutting data easily available across all client load functions
trigger a load function to rerun when data changes (e.g. $session.user = null)
a convenient writable store that is somewhat global
Because it had so many use cases in once, it became somewhat confusing what runs when, because people may only think about 4 and then wonder about 3. So I think removing it in its form was correct, but we need some features that bring back the mentioned points in a easy-to-use way. Right now we have this situation:
pass data -> can do this now by having a +layout.server.js and passing whatever you want to the client
cross-cutting data -> use await parent() -> this introduces a waterfall because you can't tell "hey I'm only interested in the data from parent X, don't wait on the 3 other layout loads after that". Something like locals for the client side would help with this.
trigger rerun -> there's nothing built-in for this right now. Rich shared a pattern somewhere about creating a custom state which triggers a unique invalidate function under the hood. Maybe it's enough to make this a blessed pattern and/or tidy it up a little and provide a wrapper around it.
convenient writable store -> again, nothing built-in, this would be this issue
3+4. It's not clear to me how to achieve a combination of these two in a nice API. session made it possible because it was on both sides.
--> I feel like we need to add recipes and/or APIs to ease this
An issue iÂīve run into a few times now is not beeing able to update $page.data client side.
Example:
You display some database rows in your app and add another row.
You call fetch and post the data to a +server endpoint or make use of the form actions.
The only option (that i know of) to get the added row is to call invalidate and reload all page related data.
This will obviously result in twice the network calls compared to just adding the newly created data to $page.data.
One way iÂīve solved this:
import{invalid}from'@sveltejs/kit';importtype{PageServerLoad,Actions}from'./$types';exportconstload: PageServerLoad=async()=>{return{// just some random test dataposts: [{title: 'Post 1'},{title: 'Post 2'},{title: 'Post 3'}]};};exportconstactions: Actions={asyncaddPost({ request }){constdata=awaitrequest.formData();consttitle=data.get('title')asstring;if(!title){returninvalid(400,{titleMissing: true});}return{newPost: { title }};}};
make it a store in +page.ts
exportconstload: PageLoad=({ data })=>{return{posts: writable(data.posts)}}
IÂīm just curious if this api/helper, if itÂīs going to be a thing, will provide an easier way to get writable stores from the client to the server in such use cases.
We can use this pattern for user-specific data, for app-wide data, and so on. It's easy to vary the type of store based on whether we're in a server or browser environment (e.g. get a snapshot of chat messages on the server, upgrade to a real time subscription in the client, etc).
Is there anything that isn't covered by this pattern, especially that needs to be resolved before 1.0?
I think this pattern is very powerful and covers most if not all use cases i can think of.
We just need some examples that make clear how and when to use this.
I long wanted to write a "State Management" section for the docs, where we also can note the "careful what to put on the server, it's shared for all requests"-stuff. This pattern could also go in there.
Reacted by David Plugge, Åukasz Polowczyk, themajashurka, AdriÃĄn Delgado, Alex and icecube11
We can use this pattern for user-specific data, for app-wide data, and so on. It's easy to vary the type of store based on whether we're in a server or browser environment (e.g. get a snapshot of chat messages on the server, upgrade to a real time subscription in the client, etc).
Is there anything that isn't covered by this pattern, especially that needs to be resolved before 1.0?
A problem with this design is that you assume the root layout to never get invalidated? (since invalidating calls the load function again. E.g. with invalidateAll()).
You might suggest the following hack: Since invalidating happens only on the browser and never on the server, you may use a global singelton on the browser for the specific store, and on the server just do what you suggested now.
But I think that the request might be deeper in some sense. I think that the core missing feature is to have global request context shared:
On the server, from the begining of the request(i.e. the server request hook) until the the end of the response computation.
On the browser, from the initialization until infinity.
By design, this "shared context" is only a memory allocation in some sense(or a whiteboard you write stuff on), it shares no information between the server and the browser, for simplicity.
This design can make data sharing much simpler while being secure, instead of passing data very carefully between server hooks and the load function.
The counter example is perhaps a bit misleading; you'd use that when you have something where the server is the source of truth, and for things like optimistic UI etc you'd update it so you don't have to trigger a load again - but if it is triggered, the value would still be correct.
That said, some way of hooking into "scoped to context on the server, global on the client" like the built-in stores could still be valuable in some contexts - but we need to see more real use cases which are not (or only weirdly) solveable with the existing solutions already.
A problem with this design is that you assume the root layout to never get invalidated? (since invalidating calls the load function again. E.g. with invalidateAll()).
WhatÂīs the problem with that? If the layout is invalidated the store will be recreated and all subsequent layouts/pages will get the new store.
Regarding the context, i remember back in the days of sapper there was a request about a function that gives you access to the load parameters. IÂīve been playing around with node:async_hooks (nextjs uses that for some context stuff aswell) which works on the server, but i donÂīt think there is anything like that for the browser. But as already suggested we can easily make it global there.
This work pretty well with some dynamic imports so we only use the context when on the server. However, i canÂīt access the event on the client, therefore i cannot make use of the custom fetch that reuses the initial data from the server.
If there was something like handle for the client the event could be stored in a global store.
Curious if this is a pattern that would fit into the sveltekit stack.
From the code snippet I don't understand how this would prevent simultaneous but separate requests from interfering with each other.
The AsyncLocalStorage class exported from node:async_hooks makes it possible to hook into the context of javascript functions.
importtype{RequestEvent}from'@sveltejs/kit';import{AsyncLocalStorage}from'node:async_hooks';exportconstrequestContext=newAsyncLocalStorage<RequestEvent>();exportconsthandle=({ event, resolve })=>{// the AsyncLocalStorage holds the event for the lifetime of the callbackreturnrequestContext.run(event,()=>resolve(event));};exportconstload=async()=>{consteventFromContext=requestContext.getStore();console.log(eventFromContext);};
async_hooks is a Node-only thing. We can't rely on it being there for in all production environments. I don't know whether our other current adapter targets automatically split out global variables per request. But even if they did, it probably wouldn't be a good idea to assume that every environment someone wants to deploy to will support either a AsyncLocalStorage-like feature or will automatically have separate global variables per each request.
A problem with this design is that you assume the root layout to never get invalidated? (since invalidating calls the load function again. E.g. with invalidateAll()).
If the root layout gets invalidated, you have a choice â return a fresh store (with data from the server, if appropriate), or (if you're in the browser) return the existing one:
I'll close this issue as I think returning stores from load basically covers all the bases. If we need to add helpers or document these patterns in future then we can, but for now I don't think there's anything we need to do
Hey I know this is closed but I'm having a hard time finding a better place - I'd just like to add that it seems like returning stores from load is exactly what I needed but that is still not very clear in the "State Management" section of the docs. @dummdidumm - assuming that it was you who wrote that section, is this intentional? Is there another discussion that found using context only is the way to go?
svelte/store is such a core part of what makes svelte awesome and it has been really difficult to understand how to replace it in sveltekit in a secure way - easily the hardest part of moving from vanilla svelte to sveltekit. Searching for other answers usually suggests to either use the now removed session, or like 50 lines of boilerplate across multiple files (exaggerating a bit but that's how it feels compared to the vanilla $storeVariable = "I love this"), so it seems I'm not the only one confused.
Maybe I'm actually just over-using stores and this is more by design but I think I'm not.
If it's just a question of updating the docs I'd be up for contributing, but want to make sure I understand it before I try!
Edit: I found this discussion (#4339). I was just searching issues before. Still doesn't super solve the documentation problem from my perspective, but some of the examples there are very good workarounds!
Activity
williamviktorsson commentedon Oct 1, 2022
Great idea. Would it make sense to provide different options of how and when the store should be created and populated. Such as âonce on first page loadâ or âfor every page loadâ or
I Imagine this might be useful for the large amount of people who enjoy integrating client side stores with responsive backend functionality such as firebase authentication / snapshot listeners.
Not sure what it would look like though or if it makes sense, or if these types of behaviors would have to be solved by each developer.
dummdidumm commentedon Oct 2, 2022
The idea sounds good, I'm not fully sure on the details yet. I think this only makes sense in the context of the shared load function, so it runs on the server on first render and is updated within the client afterwards. So locals would be the shared thing on the server and this would be the shared thing in the shared load (basically the same split as with session previously). Also, is
handlethe best place for this?handleruns for every request, but this would only be available inside the shared load function. Something likegetSessionmakes more sense to me.Another thing I'm not sure about is if this should be reserved for stores only, or if you could place arbitrary things in there. You could place arbitrary things inside stores though, and having it a non-store only makes sense for things that never update, which shouldn't live inside this anyway - so, probably fine?
PatrickG commentedon Oct 2, 2022
Instead of
createStore(request, 'whatever', request.locals.whatever);I think it would make more sense to add or set a store to the request.Something like:
Basically, we need something similar to Svelte's ContextApi, but on the server it is bound to the request, on the client it is bound to nothing.
david-plugge commentedon Oct 5, 2022
A shared object across shared load functions would be amazing! (Maybe change the name to something else since itÂīs not only about session data?)
But creating stores would make things a bit complicated. Svelte stores are pretty useless on the server side, atleast i donÂīt get the benefit. We already have
localsfor server context, eventually something likesessionfor shared context (like @dummdidumm suggested) and svelteÂīscontextfor ui context.With
$page.datawe already have a store thatÂīs always in sync and keeps all data in one spot. I wonder why thatÂīs not sufficient?Seems more like a doc thing making clear how stores work and how to safely use them with sveltekit.
david-plugge commentedon Oct 5, 2022
If itÂīs just about using something shorter than
$page.data.userthis helper can be used:dummdidumm commentedon Oct 11, 2022
Copying my Discord-thoughts into here:
What became clear to me that getSession was used for multiple things at once.
Because it had so many use cases in once, it became somewhat confusing what runs when, because people may only think about 4 and then wonder about 3. So I think removing it in its form was correct, but we need some features that bring back the mentioned points in a easy-to-use way. Right now we have this situation:
3+4. It's not clear to me how to achieve a combination of these two in a nice API. session made it possible because it was on both sides.
--> I feel like we need to add recipes and/or APIs to ease this
david-plugge commentedon Oct 18, 2022
An issue iÂīve run into a few times now is not beeing able to update
$page.dataclient side.Example:
You display some database rows in your app and add another row.
You call
fetchand post the data to a+serverendpoint or make use of the form actions.The only option (that i know of) to get the added row is to call
invalidateand reload all page related data.This will obviously result in twice the network calls compared to just adding the newly created data to
$page.data.One way iÂīve solved this:
make it a store in
+page.tsand update that store inside
+page.svelteIÂīm just curious if this api/helper, if itÂīs going to be a thing, will provide an easier way to get writable stores from the client to the server in such use cases.
Rich-Harris commentedon Nov 7, 2022
One of the lessons of
sessionwas that stores as inputs toloadis problematic. But we can return stores fromload:We can use this pattern for user-specific data, for app-wide data, and so on. It's easy to vary the type of store based on whether we're in a server or browser environment (e.g. get a snapshot of chat messages on the server, upgrade to a real time subscription in the client, etc).
Is there anything that isn't covered by this pattern, especially that needs to be resolved before 1.0?
david-plugge commentedon Nov 7, 2022
I think this pattern is very powerful and covers most if not all use cases i can think of.
We just need some examples that make clear how and when to use this.
dummdidumm commentedon Nov 7, 2022
I long wanted to write a "State Management" section for the docs, where we also can note the "careful what to put on the server, it's shared for all requests"-stuff. This pattern could also go in there.
Tal500 commentedon Nov 8, 2022
A problem with this design is that you assume the root layout to never get invalidated? (since invalidating calls the
loadfunction again. E.g. withinvalidateAll()).You might suggest the following hack: Since invalidating happens only on the browser and never on the server, you may use a global singelton on the browser for the specific store, and on the server just do what you suggested now.
But I think that the request might be deeper in some sense. I think that the core missing feature is to have global request context shared:
By design, this "shared context" is only a memory allocation in some sense(or a whiteboard you write stuff on), it shares no information between the server and the browser, for simplicity.
This design can make data sharing much simpler while being secure, instead of passing data very carefully between server hooks and the load function.
dummdidumm commentedon Nov 8, 2022
The counter example is perhaps a bit misleading; you'd use that when you have something where the server is the source of truth, and for things like optimistic UI etc you'd update it so you don't have to trigger a load again - but if it is triggered, the value would still be correct.
That said, some way of hooking into "scoped to context on the server, global on the client" like the built-in stores could still be valuable in some contexts - but we need to see more real use cases which are not (or only weirdly) solveable with the existing solutions already.
david-plugge commentedon Nov 8, 2022
WhatÂīs the problem with that? If the layout is invalidated the store will be recreated and all subsequent layouts/pages will get the new store.
david-plugge commentedon Nov 8, 2022
Regarding the
context, i remember back in the days of sapper there was a request about a function that gives you access to the load parameters. IÂīve been playing around withnode:async_hooks(nextjs uses that for some context stuff aswell) which works on the server, but i donÂīt think there is anything like that for the browser. But as already suggested we can easily make it global there.This is what iÂīve tried :
This work pretty well with some dynamic imports so we only use the context when on the server. However, i canÂīt access the event on the client, therefore i cannot make use of the custom fetch that reuses the initial data from the server.
If there was something like
handlefor the client the event could be stored in a global store.Curious if this is a pattern that would fit into the sveltekit stack.
dummdidumm commentedon Nov 8, 2022
From the code snippet I don't understand how this would prevent simultaneous but separate requests from interfering with each other.
david-plugge commentedon Nov 8, 2022
The
AsyncLocalStorageclass exported fromnode:async_hooksmakes it possible to hook into the context of javascript functions.It basicly works like svelte context.
Conduitry commentedon Nov 8, 2022
async_hooksis a Node-only thing. We can't rely on it being there for in all production environments. I don't know whether our other current adapter targets automatically split out global variables per request. But even if they did, it probably wouldn't be a good idea to assume that every environment someone wants to deploy to will support either aAsyncLocalStorage-like feature or will automatically have separate global variables per each request.david-plugge commentedon Nov 8, 2022
Yeah thatÂīs what i expected, very unfortunate. So i guess i can completely get rid of the context idea?
Rich-Harris commentedon Nov 8, 2022
If the root layout gets invalidated, you have a choice â return a fresh store (with data from the server, if appropriate), or (if you're in the browser) return the existing one:
That could be abstracted into a helper if you wanted:
I'll close this issue as I think returning stores from
loadbasically covers all the bases. If we need to add helpers or document these patterns in future then we can, but for now I don't think there's anything we need to dobrendanmatkin commentedon Mar 30, 2023
Hey I know this is closed but I'm having a hard time finding a better place - I'd just like to add that it seems like returning stores from load is exactly what I needed but that is still not very clear in the "State Management" section of the docs. @dummdidumm - assuming that it was you who wrote that section, is this intentional? Is there another discussion that found using context only is the way to go?
svelte/storeis such a core part of what makes svelte awesome and it has been really difficult to understand how to replace it in sveltekit in a secure way - easily the hardest part of moving from vanilla svelte to sveltekit. Searching for other answers usually suggests to either use the now removed session, or like 50 lines of boilerplate across multiple files (exaggerating a bit but that's how it feels compared to the vanilla$storeVariable = "I love this"), so it seems I'm not the only one confused.Maybe I'm actually just over-using stores and this is more by design but I think I'm not.
If it's just a question of updating the docs I'd be up for contributing, but want to make sure I understand it before I try!
Edit: I found this discussion (#4339). I was just searching issues before. Still doesn't super solve the documentation problem from my perspective, but some of the examples there are very good workarounds!
brendanmatkin commentedon May 8, 2023
I wrote an article that clarifies why I still think this problem isn't totally solved and maybe how the docs can be clarified. Take a look if you are interested! https://dev.to/brendanmatkin/safe-sveltekit-stores-for-ssr-5a0h