I'm needing to define what site is being accessed based on the hostname. To do this, I've setup a store:
import { get, readable } from "svelte/store"
import { page } from "$app/stores"
import { activeSite} from "$lib/Site"
import { env } from "$env/dynamic/public";
export const site = readable(activeSite(env, get(page).url.hostname))
activeSite is a very simple helper function that determines what site is currently being requested, and does so by checking against env vars to ensure that said site is in fact, supported.
The issue, is that using the page store like this isn't actually possible, because when it runs on the server it returns an error:
Cannot subscribe to 'page' store on the server outside of a Svelte component, as it is bound to the current request via component context. This prevents state from leaking between users
This is all fine and well, but I'm struggling to figure out how to do this otherwise.
One way to do this is to use a loader function on my base layout, fetch the data and then set it on the store. However, this then makes the store writable throughout the application, and it should ultimately be immutable.
Any ideas?
You could set it in a context in the layout, it then should be retrievable via getContext
in any page using said layout.
Also, the store should just be derived
, as it depends on page
. Something like:
const site = derived(page, $page => activeSite(env, $page.url.hostname))
(This change alone might fix the issue, as the module no longer directly reads page
, that should be deferred to when the store is actually first used. Depends on how/where the store is accessed, though.)