Svelte State 07 🧡 The SSR Singleton Trap — Why global .svelte.ts state leaks across users on the server in SvelteKit
In SvelteKit, server-side rendering (SSR) occurs within a persistent, long-lived Node.js process. When you define a state variable at the top level of a .svelte.ts or .ts file, that variable is initialized only once—when the module is first imported. For developers accustomed to client-side development where every user gets a fresh page reload and a clean browser context, this behavior is often surprising and dangerous.
When a user visits your application, the server-side code modifies these global variables to render the initial HTML. Because the server process is shared across all incoming requests, those modifications persist for the next user. This leads to a “Singleton Trap,” where private data like user IDs, shopping carts, or authentication tokens leak from one user’s session into another’s, creating severe security and data integrity issues.
This chapter examines why this occurs, how to detect it, and the architecture required to ensure state is scoped correctly to individual requests. We will cover the lifecycle of module-level state, the usage of request-scoped context, and patterns for isolating data.
Key point: Global variables defined at the module level in SvelteKit are shared across all requests served by the same Node.js process; therefore, any state that is user-specific must be instantiated per-request, typically within load functions, components, or through the Svelte Context API.
Why the SSR Singleton Trap exists
The shared process model. Node.js is designed for high concurrency, serving hundreds or thousands of requests within a single process. Global variables are process-wide, not request-wide.
Module evaluation lifecycle. JavaScript modules are cached after their first import. Code at the top level of a file executes exactly once during the application’s startup, regardless of how many users interact with the site.
The lack of request-local storage. Unlike some server frameworks that provide native “request-local” storage, SvelteKit relies on the developer to pass state through the load data pipeline or Svelte Context to ensure isolation.
False assumptions about clean state. Developers often assume that because a page “re-renders” for every user, the underlying server-side code is also “re-starting.” This is not true in the production runtime of a SvelteKit server.
Security and privacy risks. The most critical reason this exists is that it creates an unintentional data bridge. User A’s data is stored in a module-level $state(), and User B’s request subsequently reads that same variable, resulting in cross-user information disclosure.
a. The anatomy of the leak
When you export a state variable from a module, you create a singleton. This is useful for application-wide configuration, but fatal for request-specific data.
// ❌ The Singleton Trap: state.ts
export let userSession = $state({ id: null, name: "" });
// This module is evaluated once. Any request that modifies
// 'userSession' updates it for the entire server.
In the example above, if a load function updates userSession.name to “Alice”, the next request from “Bob” will see “Alice” in the global state. This happens because the variable exists in the module scope, which is alive for as long as the server is running.
b. Scoping state via the Context API
The correct way to handle request-specific state in SvelteKit is to define it at the component level or within a function that is invoked per request. The Context API (setContext and getContext) is designed to scope state to a tree of components, effectively isolating data to a specific request’s lifecycle.
// ✅ Scoped via Context: UserProvider.svelte
import { setContext } from 'svelte';
let { children, initialData } = $props();
// Instantiate state locally per component instance
let state = $state(initialData);
setContext('user', state);
By passing state into setContext at the root of your +layout.svelte (which runs per-request), you ensure that every request gets its own instance of that state object.
c. Using the load pipeline
SvelteKit’s load functions are the primary mechanism for getting data into a request. Instead of relying on global state, pass data down the component tree. If you need a reactive state object that is tied to a specific session, instantiate it within the load function and pass it as a prop.
// ✅ Load function: +layout.server.ts
export function load() {
return {
// Return data to be consumed by the UI
user: { id: 1, name: "Alice" }
};
}
By keeping state in the load output, you ensure that SvelteKit handles the serialization and hydration correctly, and more importantly, the data is specific to the event object of the current request.
Complete Example Session
// ============================================
// PART 1: THE LEAKY MODULE
// ============================================
// lib/global.svelte.ts
export let sharedCount = $state(0); // ❌ Global singleton!
// ============================================
// PART 2: THE REQUEST-SCOPED APPROACH
// ============================================
// lib/session.svelte.ts
export class SessionState {
count = $state(0);
}
// Do not export an instance!
// ============================================
// PART 3: PROVIDING STATE IN LAYOUT
// ============================================
// +layout.svelte
import { setContext } from 'svelte';
import { SessionState } from '$lib/session.svelte';
let session = new SessionState();
setContext('session', session);
// ============================================
// PART 4: CONSUMING STATE
// ============================================
// ChildComponent.svelte
import { getContext } from 'svelte';
let session = getContext('session');
This pattern ensures that every time a request triggers the layout, a new SessionState is created, preventing leakage.
Quick Reference
State Scoping Rules
| Pattern | Scope | SSR Safety |
|---|---|---|
Module-level $state | Global | ❌ Leaks |
Component-level $state | Per Component | ✅ Safe |
| Context-provided state | Per Request | ✅ Safe |
load function return | Per Request | ✅ Safe |
Best Practices Summary
| Action | Recommendation |
|---|---|
| User Data | Store in load or Context |
| Shared Cache | Use Map or Redis (Global) |
| UI State | Use local $state |
| Process State | Use module constants |
Best Practices
✅ Do This:
// Initialize state in the component or layout
let state = $state(initial); // ✅
// Use Context to share within a specific tree
setContext('key', state); // ✅
// Instantiate classes inside components
let session = new SessionState(); // ✅
// Rely on load() to provide server data
let { data } = $props(); // ✅
❌ Don’t Do This:
// Define state at the top of a .svelte.ts file
export let session = $state({}); // ❌
// Use a module-level variable for user data
let currentUser = $state(null); // ❌
// Expect global variables to reset per request
const globals = { clicks: 0 }; // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Shared user data | Module-level state | Use Context/Props |
| Stale state | Singleton persistence | Instantiate per-request |
| Auth leaks | Global session variable | Use locals in hooks |
| Memory bloat | Global objects kept in memory | Use scoped classes |
Real-World Examples
1. Context Provider
setContext('user', new UserState());
2. Layout Data
let { data } = $props(); // Passed from load()
3. Request Locals (Hooks)
event.locals.user = { ... }; // Safe request storage
4. Component State
let count = $state(0); // Isolated to component
5. Scoped Store
const store = writable(0); // Scoped if in component
6. Server-side caching (Global)
const cache = new Map(); // Safe (singleton intentional)
7. Session class
class UserSession { name = $state(); }
8. Layout injection
let session = getContext('session');
9. Hydration
// SvelteKit serializes data from load()
10. Memory Cleanup
// Classes get GC'd when component unmounts
Visual
The Leaky Singleton Path
┌──────────────────────────────────────────────┐
│ Request 1 (User A) ──┐ │
│ ▼ │
│ Global State (Module) ──► Value: User A │
│ ▲ │
│ Request 2 (User B) ──┘ │
│ User B sees User A's data! │
└──────────────────────────────────────────────┘
The Scoped Context Path
┌──────────────────────────────────────────────┐
│ Request 1 ──► Component ──► Context (A) │
│ │
│ Request 2 ──► Component ──► Context (B) │
│ │
│ Isolation is maintained per request. │
└──────────────────────────────────────────────┘
The Load Pipeline
┌──────────────────────────────────────────────┐
│ Load Function ──► Data Object (Per Request) │
│ │ │
│ ▼ │
│ +layout.svelte │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Scope Problem | Module-level state leaks |
| Solution | Context or load props |
| Server Environment | Shared Node.js process |
| Initialization | Once per module import |
| Best Tool | Context API |
Key takeaways:
- Global state is a singleton. Any variable defined at the top level of a module is shared across every request, leading to cross-user data leakage.
- SSR is not a per-request restart. Your code runs in a long-lived process, making module-level memory persist across user sessions.
- Use Context for request-scoping.
setContextat the layout level allows you to initialize fresh state instances that are correctly isolated to the current user’s request. - Pass data via
load. Use theloadpipeline to fetch and provide data, ensuring it is serialized and hydrated specifically for the current request. - Avoid exporting instances. Export classes or factories, but instantiate them within the Svelte component tree.
Remember: Always treat the top-level module scope in your server-side files as a shared global area. If your data is specific to a user, it must be created within the component lifecycle or injected via SvelteKit’s request-aware primitives like load or Context. When in doubt, avoid module-level $state() exports entirely.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!