r/sveltejs • • 2h ago

Change anything on this site – powered by svelte

Thumbnail levmiseri.com
5 Upvotes

A fun experiment where users can change or add anything to the site. Everything working very much thanks to the amazingness of Svelte.


r/sveltejs • • 16h ago

SvelteKit: How do you share code that uses contexts with server/non-component code?

1 Upvotes

I've been developing a site that uses a component context for handling locales/localization. I want to use some of these calls in some +page.server.ts functions, outside of a Svelte context. What is the correct/idiomatic way to write code like this? Right now I have what I feel like is a big hack that does something like this:

export const [getLocaleContext, setLocaleContext] = createContext<{ code: string }>();

let override: string | null = null

export function overrideLocalization(overrideLocale: string, body: () => void) {
    override = overrideLocale;
    try {
        body();
    } finally {
        override = null;
    }
}

function getLocale() {
    if (override) {
        return override;
    } else {
        return getLocaleContext().code
    }
}

I try to make it safer with a wrapper function and try/finally but this still feels really flimsy. Is there a better way to handle this?