Search code examples
sveltekit

Sveltekit: Sharing service objects (e.g. configured http client) across pages


I am moving my app from Svelte SPA (original) to Sveltekit multi page app (new).

In the original app, I configure a http client up top and put it context using:

setContext(HTTP_CLIENT, httpClient)

Now the entire app can get that http client using

const httpClient = getContext(HTTP_CLIENT)

I do this because my app can be started with debug parameters than turn on http request logging.


I'm not clear how to do similar in Sveltekit, because it seems that pages do not share a context.

I tried sticking the http client in the session like this:

import { session } from "$app/stores";
$session.httpClient = httpClient

and I got:

Error: Failed to serialize session data: Cannot stringify arbitrary non-POJOs

So $session is meant to be serialized, ok. Does that mean that I need to put whatever debug parameters a user supplied in $session, and each page needs to freshly instantiate its own http client? Or is there some other idiomatic sveltekit way of doing this?

PS I know sveltekit has its own fetch so you might want to say "don't use your own http client", but my app uses many different service objects (graphql client for example) that can be configured in debug (and other) modes, so please don't zero in on the fact that my example is a http client.


Solution

  • One way around this could be to send down the configuration in the top __layout file, create the http client there and store in a store. Since stores are shared across all pages the client can then freely use this store.