ISOLOCAL
ISOLOCAL
Store and access user-specific data in load functions, during SSR, and on the client without reaching for a database
Setup
// src/app.d.ts

import type { Local } from '@thetinkerinc/isolocal';

type Theme = 1 | 2 | 3 | 4;

declare global {
	namespace App {
		// Define all the values you want
		// to add to local storage
		interface Locals {
			localStorage: Local & {
				theme: Theme;
			};
		}
	}
}

export {};
1
// src/hooks.server.ts

import { sequence } from '@sveltejs/kit/hooks';
import { addLocalStorage } from '@thetinkerinc/isolocal';

// Add default values
const defaults = {
	theme: 1
};

const hooks = [addLocalStorage(defaults)];

export const handle = sequence(...hooks);
2
// src/routes/+layout.server.ts

import { getPageData } from '@thetinkerinc/isolocal';

import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async (event) => {
	return {
		...getPageData(event)
	};
};
3
// vite.config.ts

import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';

export default defineConfig({
	ssr: {
		noExternal: ['@thetinkerinc/isolocal']
	},
	plugins: [sveltekit()]
});
4
Usage
// Load functions will provide a local storage
// instance scoped to the current requiest

import code from '$lib/snippet';
import renderSnippet from '$lib/highlighter';

import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ locals }) => {
	// Grab the provided local storage instance
	const { localStorage } = locals;

	// Use local storage like normal values
	const snippet = await renderSnippet(code, localStorage.theme);

	return {
		snippet
	};
};
<script lang="ts">
// Import and use local storage directly
// in js, ts, and svelte files

let { snippet } = $props();

import local from '@thetinkerinc/isolocal';

import updateSnippet from '$lib/highlighter';

import CodeBlock from './code-block.svelte';
import ThemePicker from './theme-picker.svelte';

$effect(() => {
	// Local storage is reactive on the client
	// and can be used in $derived and $effect
	const html = updateSnippet(snippet, local.theme);
	snippet = html;
});
</script>

<CodeBlock {snippet} />
<ThemePicker onchange={(theme) => (local.theme = theme)} />