Skip to content

[feat] helper for creating stores #7105

@benmccann

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions