The user wants a "complex state management system in SvelteKit using context and stores for a large app." This is a request for architecture and code patterns, not just a simple "how to create a store" answer.
Key Requirements:
- SvelteKit: Must use SvelteKit conventions (load functions, layout files, specific module structure).
- Context: Must use
setContext and getContext to scope state (avoid global namespace pollution, enable SSR safety).
- Stores: Must use Svelte stores (
writable, readable, derived, or custom stores) to handle reactivity.
- Large App Scale: The solution needs to be modular, type-safe (TypeScript is essential), and scalable.
Core Concepts to Combine:
- Stores provide reactivity ($store syntax).
- Context provides dependency injection and scoping (state lives within the component tree, not globally).
- The "Context + Store" Pattern: You put a store into the context. This allows a parent (like
+layout.svelte) to hold the state and children to access it without prop drilling, while keeping the reactivity of stores.
Step-by-Step Implementation Plan:
-
Define the Domain: I need a hypothetical "large app" domain. An e-commerce app or a dashboard are standard examples. Let's go with a User Management & Theme system, as it covers authentication (user state) and UI preferences (settings).
-
Structure:
lib/stores/: Where store definitions live.
lib/context/: Where context keys and provider functions live.
routes/: Where the context is initialized (root layout).
-
The "Store" Layer (The Logic):
- I need a custom store interface for better abstraction.
- Let's create a
UserStore (handling auth, profile) and a ThemeStore (handling dark/light mode).
-
The "Context" Layer (The Provider):
- Instead of exporting the raw stores and importing them globally (which breaks SSR or causes singleton issues across different users on the server), we create a "Provider" function.
- This function initializes the stores with initial data (from the server/load function) and returns an interface to access them.
- We then put this interface into
setContext.
-
SSR Handling (Crucial for SvelteKit):
- Global stores are singletons on the server. If User A sets data, User B might see it.
- Solution: The stores must be created inside the component initialization (or the load function), not in a module scope.
- Refined Solution: Pass data from
+layout.server.ts -> +layout.svelte. +layout.svelte creates the stores (new instances per request) and sets them in context.
-
Drafting the Code:
- Type Definitions: Define what the state looks like (
User, AppState).
- Store Factory: A function to create the actual writable stores.
- Context Key: A symbol to avoid naming collisions.
- Context Helper:
createRootContext and useRootContext (React-like naming convention helps understanding).
-
Putting it together in a Layout:
+layout.svelte calls createRootContext(data) (where data comes from load).
- Child components call
useRootContext() to get the stores.
-
Advanced Features (to meet "Complex" requirement):
- Derived State: Combine user role + permissions.
- Methods: Actions (login, logout) attached to the store object, not just raw values. This encapsulates logic (the "Facade" pattern).
-
Refining the Code Structure:
- File 1:
lib/stores/index.ts: The actual store creation logic (Factories).
- File 2:
lib/context/app.ts: The Context glue code.
- File 3:
+layout.svelte: The entry point.
-
Self-Correction/Review:
- Critique: Is it too complex?
- Adjustment: Keep the implementation clean. Use TypeScript generics. Emphasize why this pattern is used (SSR safety).
- Critique: What about cross-module communication?
- Adjustment: Show how a specific feature store (e.g., Cart) can be nested inside the root or managed separately. For simplicity, I'll stick to a Root App Context containing distinct domain stores.
-
Final Output Generation Strategy:
- Introduction: Explain the "Store-in-Context" pattern.
- Step 1: Define Types.
- Step 2: The Store Factory (The Logic).
- Step 3: The Context Provider (The Glue).
- Step 4: The Layout (The Entry).
- Step 5: Usage in Components.
- Summary of benefits.
(Self-Correction during drafting code): I should ensure I handle the "initial state" passing. The server loads data (load function), passes it to the page, page passes it to the Context initialization. This is the SvelteKit way.
Let's write the code.
types.ts: User, Theme.
store-factory.ts: Function returning { subscribe, set, update } or a custom object with methods.
context.ts: key = Symbol(). setAppContext(initial). getAppContext().
+layout.svelte: <script> context = setAppContext(data); </script> <slot />
+page.svelte: <script> ctx = getAppContext(); </script> Hello {$ctx.user.name}
This looks solid. It solves the "large app" problem by decoupling state from components, solves the "SSR" problem by avoiding global singletons, and solves "reactivity" by using Svelte stores.
Managing state in a large SvelteKit application requires a balance between reactivity (using Svelte Stores) and dependency injection/scoping (using Svelte Context).
For a large app, the "Store-in-Context" pattern is widely considered the best practice. This approach prevents the "prop-drilling" problem, avoids the "global singleton" pitfalls (where state leaks between users on the server during SSR), and keeps your architecture modular.
Here is a complete implementation guide.
The Architecture
- Domain Stores: We define the logic using Svelte stores (
writable, derived).
- Context Interface: We define a TypeScript interface for the state.
- Context Provider: A root layout that initializes the state and sets it into the context tree.
- Consumer Hooks: Helper functions to retrieve the state from context in child components.
Step 1: Define Domain State (The Logic)
We will create a modular state container. For this example, we'll build a UserStore (authentication) and a CartStore (domain logic).
Create a file at src/lib/stores/appStore.ts.
import { writable, derived, get } from 'svelte/store';
import type { Writable, Readable } from 'svelte/store';
// --- Types ---
export interface User {
id: string;
name: string;
role: 'admin' | 'user';
}
export interface CartItem {
id: string;
name: string;
price: number;
qty: number;
}
// --- 1. User Store (Authentication) ---
function createUserStore() {
const { subscribe, set, update } = writable<User | null>(null);
return {
subscribe,
login: (name: string) => set({ id: '123', name, role: 'user' }),
logout: () => set(null),
// Hydrate from server data
init: (initialUser: User | null) => set(initialUser)
};
}
// --- 2. Cart Store (Complex Logic) ---
function createCartStore() {
const items = writable<CartItem[]>([]);
// Derived state: calculate totals automatically
const total = derived(items, ($items) =>
$items.reduce((sum, item) => sum + item.price * item.qty, 0)
);
return {
items,
total,
addItem: (item: Omit<CartItem, 'qty'>) => {
items.update((existing) => {
const found = existing.find(i => i.id === item.id);
if (found) {
found.qty += 1;
return existing;
}
return [...existing, { ...item, qty: 1 }];
});
},
removeItem: (id: string) => {
items.update((existing) => existing.filter(i => i.id !== id));
},
clear: () => items.set([])
};
}
// --- 3. Aggregate Root ---
// This combines all stores into a single object to put into context
export const createAppState = (initialUser: User | null = null) => {
const user = createUserStore();
const cart = createCartStore();
// Initialize with server data if available
if (initialUser) {
user.init(initialUser);
}
return {
user,
cart
};
};
// Define the Type of our Context
export type AppState = ReturnType<typeof createAppState>;
Step 2: The Context Key and Helpers
In Svelte, context is keyed by unique symbols. To avoid "undefined context" errors, we create a robust helper to set and get the context.
Create src/lib/context/appContext.ts.
import { getContext, setContext } from 'svelte';
import type { AppState } from '$lib/stores/appStore';
// Unique key for the context
const APP_CONTEXT_KEY = Symbol('app-state');
export function setAppState(state: AppState) {
setContext(APP_CONTEXT_KEY, state);
}
export function getAppState(): AppState {
const state = getContext<AppState>(APP_CONTEXT_KEY);
if (!state) {
throw new Error(
'AppState not found in context. Did you forget to call setAppState() in a parent layout?'
);
}
return state;
}
// Optional: Create specific hooks for cleaner code in components
export function useUser() {
const { user } = getAppState();
return user;
}
export function useCart() {
const { cart } = getAppState();
return cart;
}
Step 3: The Root Layout (Server-Side Integration)
This is the most critical part. We must instantiate the stores per request (inside the component instance) rather than globally. This ensures that User A doesn't get User B's cart data.
In src/routes/+layout.svelte:
<script lang="ts">
import { onMount } from 'svelte';
import { createAppState } from '$lib/stores/appStore';
import { setAppState } from '$lib/context/appContext';
// Data passed from the server load function
// Assuming you have a `export const load` in +layout.server.ts
// that returns { user: ... }
let { data } = $props();
// 1. Create the state instance.
// This runs on the server for SSR and again in the browser for hydration.
// We pass the initial user data from the server.
const appState = createAppState(data.user);
// 2. Set it into Svelte's context API.
// This makes 'appState' available to every child component and page.
setAppState(appState);
// Note: We do not need onMount to initialize stores if data is passed directly.
// The reactivity of $props() handles updates if server data changes.
</script>
<div class="app-shell">
<nav>
<!-- You can use the store directly here if this layout persists -->
<!-- Or just render the slot -->
</nav>
<main>
<slot />
</main>
</div>
Note: In +layout.server.ts, you would typically fetch the current user session and return it so data.user is populated.
Step 4: Usage in Child Components
Now, any page or component deep within the tree can access the state without props.
In a Page (src/routes/cart/+page.svelte)
We use the useCart hook. Because the store is reactive, the UI updates immediately.
<script lang="ts">
import { useCart } from '$lib/context/appContext';
import { Button } from '$lib/components/ui/button'; // hypothetical component
const cart = useCart();
// Destructure stores for auto-subscription in the template
const { items, total } = cart;
</script>
<div class="cart-page">
<h1>Your Cart</h1>
{#if $items.length === 0}
<p>Cart is empty</p>
{:else}
<ul>
{#each $items as item}
<li>
{item.name} x {item.qty} - ${item.price}
<Button onclick={() => cart.removeItem(item.id)}>Remove</Button>
</li>
{/each}
</ul>
<!-- Derived state updates automatically -->
<h3>Total: ${$total}</h3>
{/if}
</div>
In a Component (e.g., User Header)
<script lang="ts">
import { useUser } from '$lib/context/appContext';
const user = useUser();
</script>
<header>
{#if $user}
<span>Welcome, {$user.name}</span>
<button onclick={() => user.logout()}>Logout</button>
{:else}
<a href="/login">Login</a>
{/if}
</header>
Why this pattern scales
- SSR Safety:
createAppState is called inside the component script, meaning a new instance is created for every server request. You won't leak data between users.
- Testability: You can easily write unit tests for components by importing
setAppState and passing in a mock state before mounting the component.
- Decoupling: Components import the hook (
useCart), not the global singleton. You can swap the implementation of createAppState later without breaking components.
- Reactivity: You keep the full power of Svelte stores (subscriptions, derived values) but encapsulated within a managed scope.
Summary of Folder Structure
src/
├── lib/
│ ├── context/
│ │ └── appContext.ts # The "glue" (setContext/getContext helpers)
│ ├── stores/
│ │ └── appStore.ts # The business logic (Factories)
│ └── components/
│ └── Header.svelte # Consumes context via hooks
├── routes/
│ ├── +layout.server.ts # Fetches initial user data
│ ├── +layout.svelte # Instantiates State & Sets Context
│ └── cart/
│ └── +page.svelte # Consumes Context