This is a great question about state management in SvelteKit. The user wants to:
- Create a global store with complex state management
- Sync with localStorage
- Only sync on client side (handle SSR properly)
- Prevent SSR mismatch issues
Let me create a comprehensive solution that includes:
- A custom store implementation
- Proper SSR detection
- localStorage integration
- Hydration handling
- Type safety (TypeScript)
- Examples of usage
- Error handling
I'll provide a complete, production-ready implementation with:
- Custom writable stores with localStorage support
- Proper browser detection
- Correct hydration patterns for SvelteKit
- Example stores (user, theme, cart, etc.)
- Components showing usage
- Tests/examples
- Best practices
Let me structure this comprehensively:
- A utility to detect browser environment
- A factory function to create stores with localStorage sync
- Multiple store examples
- A hydration component
- Usage examples in components
- Configuration and best practices
Complex State Management in SvelteKit with localStorage Sync
I'll create a robust solution that handles SSR mismatches and syncs state with localStorage safely.
1. Browser Detection Utility
// src/lib/utils/browser.ts
export const isBrowser = (): boolean => {
return typeof window !== 'undefined' && typeof document !== 'undefined';
};
export const canAccessLocalStorage = (): boolean => {
try {
if (!isBrowser()) return false;
const test = '__test__';
localStorage.setItem(test, test);
localStorage.removeItem(test);
return true;
} catch {
return false;
}
};
2. Custom Store Factory with localStorage Sync
// src/lib/stores/createPersistentStore.ts
import { writable, type Writable } from 'svelte/store';
import { isBrowser } from '$lib/utils/browser';
export interface PersistentStoreOptions<T> {
key: string;
initialValue: T;
version?: number;
onHydrate?: (value: T) => T | Promise<T>;
serialize?: (value: T) => string;
deserialize?: (value: string) => T;
}
/**
* Creates a store that syncs with localStorage
* Handles SSR by deferring reads until browser environment
*/
export function createPersistentStore<T>(
options: PersistentStoreOptions<T>
): Writable<T> & {
hydrate: () => Promise<void>;
reset: () => void;
clear: () => void;
} {
const {
key,
initialValue,
version = 1,
onHydrate,
serialize = JSON.stringify,
deserialize = JSON.parse,
} = options;
// Create base store
const { subscribe, set, update } = writable<T>(initialValue);
// Internal state
let isHydrated = false;
let mounted = false;
// Load from localStorage
const loadFromStorage = (defaultValue: T): T => {
if (!isBrowser()) return defaultValue;
try {
const stored = localStorage.getItem(key);
if (stored === null) return defaultValue;
const data = deserialize(stored);
// Validate version if needed
if (data && typeof data === 'object' && 'version' in data) {
if (data.version !== version) {
console.warn(
`Store version mismatch for "${key}". Expected ${version}, got ${data.version}`
);
return defaultValue;
}
return data.value;
}
return data;
} catch (error) {
console.error(`Failed to load store "${key}":`, error);
return defaultValue;
}
};
// Save to localStorage
const saveToStorage = (value: T): void => {
if (!isBrowser()) return;
try {
const data = {
version,
value,
timestamp: Date.now(),
};
localStorage.setItem(key, serialize(data));
} catch (error) {
console.error(`Failed to save store "${key}":`, error);
}
};
// Hydrate from localStorage
const hydrate = async (): Promise<void> => {
if (isHydrated || !isBrowser()) return;
try {
let value = loadFromStorage(initialValue);
// Apply custom hydration logic if provided
if (onHydrate) {
value = await onHydrate(value);
}
set(value);
isHydrated = true;
} catch (error) {
console.error(`Failed to hydrate store "${key}":`, error);
set(initialValue);
}
};
// Subscribe to changes and persist
const unsubscribe = subscribe((value) => {
if (mounted && isHydrated) {
saveToStorage(value);
}
});
// Custom setter with persistence
const persistentSet = (value: T): void => {
set(value);
saveToStorage(value);
};
// Custom updater with persistence
const persistentUpdate = (updater: (value: T) => T): void => {
update((current) => {
const next = updater(current);
saveToStorage(next);
return next;
});
};
// Reset to initial value
const reset = (): void => {
set(initialValue);
if (isBrowser()) {
localStorage.removeItem(key);
}
};
// Clear storage
const clear = (): void => {
reset();
isHydrated = false;
};
// Mark as mounted
if (isBrowser()) {
mounted = true;
}
return {
subscribe,
set: persistentSet,
update: persistentUpdate,
hydrate,
reset,
clear,
};
}
3. Global Application State Store
// src/lib/stores/appStore.ts
import { derived } from 'svelte/store';
import { createPersistentStore } from './createPersistentStore';
// Types
export interface User {
id: string;
name: string;
email: string;
preferences: {
theme: 'light' | 'dark' | 'auto';
language: string;
notifications: boolean;
};
}
export interface Theme {
mode: 'light' | 'dark';
accentColor: string;
}
export interface CartItem {
id: string;
quantity: number;
price: number;
}
export interface Cart {
items: CartItem[];
updatedAt: number;
}
export interface AppState {
user: User | null;
theme: Theme;
cart: Cart;
sidebarOpen: boolean;
}
// Initial state
const initialAppState: AppState = {
user: null,
theme: {
mode: 'light',
accentColor: '#3b82f6',
},
cart: {
items: [],
updatedAt: Date.now(),
},
sidebarOpen: false,
};
/**
* Main application store with localStorage persistence
*/
export const appStore = createPersistentStore<AppState>({
key: 'app-state',
initialValue: initialAppState,
version: 1,
onHydrate: async (value) => {
// Custom validation/transformation on hydration
return {
...value,
// Reset user on page reload for security
user: null,
};
},
serialize: (value) => {
// Custom serialization
return JSON.stringify(value, null, 2);
},
deserialize: JSON.parse,
});
/**
* Derived stores for specific slices
*/
export const userStore = derived(appStore, ($app) => $app.user);
export const themeStore = derived(appStore, ($app) => $app.theme);
export const cartStore = derived(appStore, ($app) => $app.cart);
export const cartTotalStore = derived(cartStore, ($cart) => {
return $cart.items.reduce((total, item) => total + item.price * item.quantity, 0);
});
export const cartCountStore = derived(cartStore, ($cart) => {
return $cart.items.reduce((count, item) => count + item.quantity, 0);
});
/**
* Actions
*/
export const appActions = {
// User actions
setUser: (user: User) => {
appStore.update((state) => ({
...state,
user,
}));
},
clearUser: () => {
appStore.update((state) => ({
...state,
user: null,
}));
},
updateUserPreferences: (preferences: Partial<User['preferences']>) => {
appStore.update((state) => ({
...state,
user: state.user
? {
...state.user,
preferences: {
...state.user.preferences,
...preferences,
},
}
: null,
}));
},
// Theme actions
setTheme: (theme: Theme) => {
appStore.update((state) => ({
...state,
theme,
}));
},
toggleThemeMode: () => {
appStore.update((state) => ({
...state,
theme: {
...state.theme,
mode: state.theme.mode === 'light' ? 'dark' : 'light',
},
}));
},
// Cart actions
addToCart: (item: CartItem) => {
appStore.update((state) => {
const existingItem = state.cart.items.find((i) => i.id === item.id);
return {
...state,
cart: {
items: existingItem
? state.cart.items.map((i) =>
i.id === item.id
? { ...i, quantity: i.quantity + item.quantity }
: i
)
: [...state.cart.items, item],
updatedAt: Date.now(),
},
};
});
},
removeFromCart: (itemId: string) => {
appStore.update((state) => ({
...state,
cart: {
items: state.cart.items.filter((i) => i.id !== itemId),
updatedAt: Date.now(),
},
}));
},
updateCartItem: (itemId: string, quantity: number) => {
appStore.update((state) => ({
...state,
cart: {
items: state.cart.items.map((i) =>
i.id === itemId ? { ...i, quantity } : i
),
updatedAt: Date.now(),
},
}));
},
clearCart: () => {
appStore.update((state) => ({
...state,
cart: {
items: [],
updatedAt: Date.now(),
},
}));
},
// UI actions
toggleSidebar: () => {
appStore.update((state) => ({
...state,
sidebarOpen: !state.sidebarOpen,
}));
},
setSidebarOpen: (open: boolean) => {
appStore.update((state) => ({
...state,
sidebarOpen: open,
}));
},
};
4. Hydration Component
<!-- src/lib/components/Hydrator.svelte -->
<script lang="ts">
import { onMount } from 'svelte';
import { appStore } from '$lib/stores/appStore';
import { isBrowser } from '$lib/utils/browser';
let isHydrated = false;
onMount(async () => {
if (isBrowser()) {
await appStore.hydrate();
isHydrated = true;
}
});
</script>
{#if !isHydrated && isBrowser()}
<div class="hydrator-loading">
<div class="spinner" />
<p>Loading state...</p>
</div>
{:else}
<slot />
{/if}
<style>
.hydrator-loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
gap: 1rem;
}
.spinner {
width: 2rem;
height: 2rem;
border: 3px solid rgba(0, 0, 0, 0.1);
border-top-color: #3b82f6;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
5. Root Layout with Hydration
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { onMount } from 'svelte';
import { appStore, themeStore } from '$lib/stores/appStore';
import Hydrator from '$lib/components/Hydrator.svelte';
import '../app.css';
let mounted = false;
onMount(() => {
mounted = true;
});
$: if (mounted && $themeStore.mode === 'dark') {
document.documentElement.classList.add('dark');
} else if (mounted) {
document.documentElement.classList.remove('dark');
}
</script>
<Hydrator>
<div class="app">
<slot />
</div>
</Hydrator>
<style>
:global(html) {
transition: background-color 0.3s, color 0.3s;
}
:global(html.dark) {
color-scheme: dark;
background-color: #1f2937;
color: #f3f4f6;
}
:global(html.light) {
color-scheme: light;
background-color: #ffffff;
color: #1f2937;
}
.app {
min-height: 100vh;
}
</style>
6. Usage Examples
Cart Component
<!-- src/lib/components/Cart.svelte -->
<script lang="ts">
import { cartStore, cartCountStore, cartTotalStore, appActions } from '$lib/stores/appStore';
</script>
<div class="cart-widget">
<div class="cart-header">
<h2>Shopping Cart</h2>
<span class="cart-count">{$cartCountStore}</span>
</div>
{#if $cartStore.items.length === 0}
<p class="empty-message">Your cart is empty</p>
{:else}
<div class="cart-items">
{#each $cartStore.items as item (item.id)}
<div class="cart-item">
<div class="item-details">
<p class="item-id">{item.id}</p>
<p class="item-price">${item.price.toFixed(2)}</p>
</div>
<div class="item-quantity">
<button
on:click={() => appActions.updateCartItem(item.id, Math.max(1, item.quantity - 1))}
>
−
</button>
<span>{item.quantity}</span>
<button on:click={() => appActions.updateCartItem(item.id, item.quantity + 1)}>
+
</button>
</div>
<button class="remove-btn" on:click={() => appActions.removeFromCart(item.id)}>
Remove
</button>
</div>
{/each}
</div>
<div class="cart-footer">
<div class="total">
<strong>Total:</strong>
<span>${$cartTotalStore.toFixed(2)}</span>
</div>
<button class="clear-btn" on:click={() => appActions.clearCart()}>
Clear Cart
</button>
<button class="checkout-btn">Checkout</button>
</div>
{/if}
</div>
<style>
.cart-widget {
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
padding: 1.5rem;
background: white;
}
.cart-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.cart-count {
background: #3b82f6;
color: white;
border-radius: 50%;
width: 2rem;
height: 2rem;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
.empty-message {
text-align: center;
color: #6b7280;
padding: 2rem;
}
.cart-items {
display: flex;
flex-direction: column;
gap: 1rem;
margin-bottom: 1rem;
}
.cart-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
background: #f9fafb;
border-radius: 0.375rem;
}
.item-quantity {
display: flex;
align-items: center;
gap: 0.5rem;
}
.item-quantity button {
width: 2rem;
height: 2rem;
border: 1px solid #d1d5db;
background: white;
cursor: pointer;
border-radius: 0.25rem;
}
.remove-btn {
padding: 0.5rem 1rem;
background: #ef4444;
color: white;
border: none;
border-radius: 0.375rem;
cursor: pointer;
}
.cart-footer {
display: flex;
flex-direction: column;
gap: 1rem;
}
.total {
display: flex;
justify-content: space-between;
font-size: 1.125rem;
}
.clear-btn,
.checkout-btn {
padding: 0.75rem;
border: none;
border-radius: 0.375rem;
cursor: pointer;
font-weight: 500;
}
.clear-btn {
background: #f3f4f6;
}
.checkout-btn {
background: #10b981;
color: white;
}
</style>
Theme Toggle
<!-- src/lib/components/ThemeToggle.svelte -->
<script lang="ts">
import { themeStore, appActions } from '$lib/stores/appStore';
</script>
<button class="theme-toggle" on:click={() => appActions.toggleThemeMode()}>
{#if $themeStore.mode === 'light'}
<span>🌙</span>
{:else}
<span>☀️</span>
{/if}
{$themeStore.mode}
</button>
<style>
.theme-toggle {
padding: 0.5rem 1rem;
background: #f3f4f6;
border: 1px solid #d1d5db;
border-radius: 0.375rem;
cursor: pointer;
font-weight: 500;
display: flex;
align-items: center;
gap: 0.5rem;
}
:global(html.dark) .theme-toggle {
background: #374151;
border-color: #4b5563;
color: #f3f4f6;
}
</style>
Home Page Example
<!-- src/routes/+page.svelte -->
<script lang="ts">
import { userStore, appActions } from '$lib/stores/appStore';
import Cart from '$lib/components/Cart.svelte';
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
function addSampleItem() {
appActions.addToCart({
id: `item-${Date.now()}`,
quantity: 1,
price: Math.random() * 100,
});
}
function setUser() {
appActions.setUser({
id: '1',
name: 'John Doe',
email: 'john@example.com',
preferences: {
theme: 'light',
language: 'en',
notifications: true,
},
});
}
</script>
<div class="container">
<header>
<h1>SvelteKit Store Management</h1>
<ThemeToggle />
</header>
<main>
{#if $userStore}
<section class="user-section">
<h2>Welcome, {$userStore.name}!</h2>
<p>Email: {$userStore.email}</p>
<button on:click={() => appActions.clearUser()}>Logout</button>
</section>
{:else}
<section class="user-section">
<p>Not logged in</p>
<button on:click={setUser}>Login (Demo)</button>
</section>
{/if}
<section>
<h2>Shopping</h2>
<button on:click={addSampleItem}>Add Random Item</button>
</section>
<Cart />
</main>
</div>
<style>
.container {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 2rem;
border-bottom: 2px solid #e5e7eb;
padding-bottom: 1rem;
}
main {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
margin-bottom: 2rem;
}
section {
padding: 1.5rem;
border: 1px solid #e5e7eb;
border-radius: 0.5rem;
}
button {
padding: 0.5rem 1rem;
background: #3b82f6;
color: white;
border: none;
border-radius: 0.375rem;
cursor: pointer;
font-weight: 500;
}
button:hover {
background: #2563eb;
}
:global(html.dark) section {
background: #374151;
border-color: #4b5563;
}
</style>
7. Advanced: Time-Travel Debugging Store
// src/lib/stores/debugStore.ts
import { writable } from 'svelte/store';
export interface StateSnapshot {
timestamp: number;
state: any;
action: string;
}
class StateDebugger {
private snapshots: StateSnapshot[] = [];
private maxSnapshots = 50;
recordSnapshot(state: any, action: string): void {
this.snapshots.push({
timestamp: Date.now(),
state: JSON.parse(JSON.stringify(state)),
action,
});
// Keep only recent snapshots
if (this.snapshots.length > this.maxSnapshots) {
this.snapshots = this.snapshots.slice(-this.maxSnapshots);
}
}
getSnapshots(): StateSnapshot[] {
return this.snapshots;
}
rewind(index: number): any {
return this.snapshots[index]?.state;
}
clear(): void {
this.snapshots = [];
}
}
export const stateDebugger = new StateDebugger();
export const debugSnapshots = writable<StateSnapshot[]>([]);
// Export function to update debugging UI
export function updateDebugger(state: any, action: string): void {
stateDebugger.recordSnapshot(state, action);
debugSnapshots.set(stateDebugger.getSnapshots());
}
8. Configuration & Best Practices
// src/lib/config/storeConfig.ts
export const STORE_CONFIG = {
// localStorage keys
STORAGE_KEYS: {
APP_STATE: 'app-state',
USER_PREFERENCES: 'user-preferences',
CACHE: 'app-cache',
},
// Expiration times (in ms)
EXPIRATION: {
SESSION: 24 * 60 * 60 * 1000, // 24 hours
CACHE: 60 * 60 * 1000, // 1 hour
},
// Size limits
LIMITS: {
MAX_STORE_SIZE: 5 * 1024 * 1024, // 5MB
MAX_SNAPSHOTS: 50,
},
// Flags
DEBUG: import.meta.env.DEV,
PERSIST_ON_ERROR: true,
};
// src/lib/stores/index.ts
export * from './appStore';
export * from './createPersistentStore';
export { stateDebugger, debugSnapshots } from './debugStore';
Key Features
✅ SSR-Safe: Detects browser environment before reading localStorage
✅ Type-Safe: Full TypeScript support
✅ Hydration: Proper handling of client-side hydration
✅ Persistence: Auto-save to localStorage
✅ Derived Stores: Efficient computed selectors
✅ Error Handling: Graceful fallbacks
✅ Version Control: Store versioning support
✅ Custom Serialization: Support for complex types
✅ Time-Travel Debugging: Track state changes
✅ React to State: Derived stores trigger UI updates
This solution provides enterprise-grade state management for SvelteKit!