Skip to content

[feat] helper for creating stores #7105

Closed as not planned
Closed as not planned

Description

@benmccann

Describe the problem

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.

We could have an API like:

export const getStore = function(key, request) {
  return request ? WEAK_MAP.get(request).get(key) : getContext(key);
};

When we're going to start rendering the templates we could populate the context from the map.

We could also have a method to create a store. Being able to call it in handle would solve #7107:

createStore(request, 'whatever', request.locals.whatever);

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

Activity

  1. added this to the 1.0 milestone on Oct 1, 2022
  2. williamviktorsson commented on Oct 1, 2022

    @williamviktorsson
    Contributor

    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.

  3. dummdidumm commented on Oct 2, 2022

    @dummdidumm
    Member

    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?

  4. PatrickG commented on Oct 2, 2022

    @PatrickG
    Member

    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:

    import type { Readable } from 'svelte/store';
    function set/addStore<T extends Readable = Readable>(key: any; store: T): void;
    function getStore<T extends Readable = Readable>(key: any): T;

    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.

  5. david-plugge commented on Oct 5, 2022

    @david-plugge
    Contributor

    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.

  6. david-plugge commented on Oct 5, 2022

    @david-plugge
    Contributor

    If itÂīs just about using something shorter than $page.data.user this helper can be used:

    import type { Page } from '@sveltejs/kit';
    import { browser } from '$app/environment';
    import { page } from '$app/stores';
    import { derived, type Readable } from 'svelte/store';
    
    function derivedFromPage<T>(fn: (page: Page) => T): Readable<T> {
    	let store: Readable<T>;
    
    	return {
    		subscribe(run, invalidate?) {
    			if (!browser || !store) store = derived(page, fn);
    			return store.subscribe(run, invalidate);
    		}
    	};
    }
    
    export const user = derivedFromPage(($page) => $page.data.user);
  7. dummdidumm commented on Oct 11, 2022

    @dummdidumm
    Member

    Copying my Discord-thoughts into here:

    What became clear to me that getSession was used for multiple things at once.

    1. pass data from server to client load functions
    2. make cross-cutting data easily available across all client load functions
    3. trigger a load function to rerun when data changes (e.g. $session.user = null)
    4. 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:

    1. pass data -> can do this now by having a +layout.server.js and passing whatever you want to the client
    2. 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.
    3. 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.
    4. 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

  8. david-plugge commented on Oct 18, 2022

    @david-plugge
    Contributor

    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';
    import type { PageServerLoad, Actions } from './$types';
    
    export const load: PageServerLoad = async () => {
    	return {
    		// just some random test data
    		posts: [{ title: 'Post 1' }, { title: 'Post 2' }, { title: 'Post 3' }]
    	};
    };
    
    export const actions: Actions = {
    	async addPost({ request }) {
    		const data = await request.formData();
    		const title = data.get('title') as string;
    
    		if (!title) {
    			return invalid(400, {
    				titleMissing: true
    			});
    		}
    		return {
    			newPost: { title }
    		};
    	}
    };

    make it a store in +page.ts

    export const load: PageLoad = ({ data }) => {
    	return {
    		posts: writable(data.posts)
    	}
    }

    and update that store inside +page.svelte

    <script lang="ts">
    	import { applyAction, enhance, type SubmitFunction } from '$app/forms';
    	import type { PageData, ActionData } from './$types';
    
    	export let form: ActionData;
    	export let data: PageData;
    
    	$: posts = data.posts;
    
    	const handleAddPost: SubmitFunction<{ newPost: { title: string } }> =
    		() =>
    		async ({ result, update }) => {
    			if (result.type === 'success') {
    				await applyAction(result);
    
    				posts.update(($posts) => {
    					$posts.push(result.data!.newPost);
    					return $posts;
    				});
    				return;
    			}
    			update();
    		};
    </script>
    
    <ul>
    	{#each $posts as item}
    		<li>{item.title}</li>
    	{/each}
    </ul>
    
    <form action="?/addPost" method="post" use:enhance={handleAddPost}>
    	{#if form?.titleMissing}
    		<p class="error">Please enter a title</p>
    	{/if}
    	<input name="title" type="text" placeholder="Title" />
    	<button type="submit">Submit</button>
    </form>

    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.

  9. Rich-Harris commented on Nov 7, 2022

    @Rich-Harris
    Member

    One of the lessons of session was that stores as inputs to load is problematic. But we can return stores from load:

    // src/routes/+layout.js
    export function load() {
      return {
        count: writable(0)
      };
    }
    <!-- src/routes/+page.svelte -->
    <script>
      import { page } from '$app/stores';
    
      $: count = $page.data.count;
    </script>
    
    <button on:click={() => $count += 1}>clicks: {$count}</button>

    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?

  10. david-plugge commented on Nov 7, 2022

    @david-plugge
    Contributor

    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.

  11. dummdidumm commented on Nov 7, 2022

    @dummdidumm
    Member

    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.

  12. Tal500 commented on Nov 8, 2022

    @Tal500
    Contributor

    One of the lessons of session was that stores as inputs to load is problematic. But we can return stores from load:

    // src/routes/+layout.js
    export function load() {
      return {
        count: writable(0)
      };
    }
    <!-- src/routes/+page.svelte -->
    <script>
      import { page } from '$app/stores';
    
      $: count = $page.data.count;
    </script>
    
    <button on:click={() => $count += 1}>clicks: {$count}</button>

    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.

  13. dummdidumm commented on Nov 8, 2022

    @dummdidumm
    Member

    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.

  14. david-plugge commented on Nov 8, 2022

    @david-plugge
    Contributor

    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.

  15. david-plugge commented on Nov 8, 2022

    @david-plugge
    Contributor

    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 is what iÂīve tried :

    // src/hooks.server.ts
    import { setRequestContext } from 'my-lib';
    
    export const handle = ({ resolve, event }) => {
    	return runWithRequestContext(event, () => resolve(event));
    }
    
    // src/lib/api.ts
    import { getLoadContext } from 'my-lib';
    
    export function post() {
    	const { fetch } = getRequestContext();
    	return fetch(...);
    }
    
    // src/routes/+page.ts
    export const load = async () => {
    	const data = await post();
    }

    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.

  16. dummdidumm commented on Nov 8, 2022

    @dummdidumm
    Member

    From the code snippet I don't understand how this would prevent simultaneous but separate requests from interfering with each other.

  17. david-plugge commented on Nov 8, 2022

    @david-plugge
    Contributor

    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.

    import type { RequestEvent } from '@sveltejs/kit';
    import { AsyncLocalStorage } from 'node:async_hooks';
    
    export const requestContext = new AsyncLocalStorage<RequestEvent>();
    
    export const handle = ({ event, resolve }) => {
    	// the AsyncLocalStorage holds the event for the lifetime of the callback
    	return requestContext.run(event, () => resolve(event));
    };
    
    export const load = async () => {
    	const eventFromContext = requestContext.getStore();
    
    	console.log(eventFromContext);
    };

    It basicly works like svelte context.

  18. Conduitry commented on Nov 8, 2022

    @Conduitry
    Member

    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.

  19. david-plugge commented on Nov 8, 2022

    @david-plugge
    Contributor

    Yeah thatÂīs what i expected, very unfortunate. So i guess i can completely get rid of the context idea?

  20. Rich-Harris commented on Nov 8, 2022

    @Rich-Harris
    Member

    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:

    // src/routes/+layout.js
    import { browser } from '$app/environment';
    import { writable } from 'svelte/store';
    
    let store;
    
    export function load() {
      return {
        count: browser ? (store || (store = writable(0))) : writable(0)
      };
    }

    That could be abstracted into a helper if you wanted:

    // src/lib/cache.js
    import { browser } from '$app/environment';
    
    const cache = new Map();
    
    export function createCachedValue(key, fn) {
      if (cache.has(key)) return cache.get(key);
      const value = fn();
      if (browser) cache.set(key, value);
      return value;
    }
    // src/routes/+layout.js
    import { createCachedValue } from '$lib/cache';
    import { writable } from 'svelte/store';
    
    export function load() {
      return {
        count: createCachedValue('count', () => writable(0))
      };
    }

    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

  21. brendanmatkin commented on Mar 30, 2023

    @brendanmatkin

    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!

  22. brendanmatkin commented on May 8, 2023

    @brendanmatkin

    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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions