This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte5-runes-ssr-scope-isolation-standard

Svelte 5 Runes SSR Reactive Scope Isolation & Context Encapsulation

Enforces strict lexical and contextual isolation for Svelte 5 reactive runes in SSR environments. Module-level $state declarations share memory across concurrent requests in persistent Node.js/edge worker runtimes, causing critical cross-tenant data contamination and memory leaks. Mutable reactive proxies must strictly be encapsulated within request-scoped contexts, factory functions, or component instances.

Prohibited Anti-Pattern: Module-Level $state Declarations Causing Cross-Request State Pollution in SvelteKit SSR

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes SSR Reactive Scope Isolation & Context Encapsulation - Enforces strict lexical and contextual isolation for Svelte 5 reactive runes in SSR environments. Module-level $state declarations share memory across concurrent requests in persistent Node.js/edge worker runtimes, causing critical cross-tenant data contamination and memory leaks. Mutable reactive proxies must strictly be encapsulated within request-scoped contexts, factory functions, or component instances.
globs: src/**/*.svelte, src/**/*.svelte.ts, src/**/*.svelte.js, src/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte5-runes-ssr-scope-isolation-standard"
---

# Svelte 5 Runes SSR Reactive Scope Isolation & Context Encapsulation

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Module-Level $state Declarations Causing Cross-Request State Pollution in SvelteKit SSR

## System Constraints
You are a Principal Engineer enforcing Svelte 5 Runes SSR Reactive Scope Isolation Standard. Mandate that all mutable $state declarations are isolated per request via Svelte's Context API or request-scoped factories, preventing cross-tenant data leakage and server memory retention.

## Strict Guidelines
- Engineers MUST NEVER declare mutable `$state` or `$state.raw` at the top level of `.svelte.ts` or `.svelte` modules evaluated during SSR.
- Engineers MUST encapsulate shared reactive domain logic within class instances or closures instantiated inside component lifecycles or SvelteKit request hooks.
- Code MUST use Svelte 5's `setContext` and `getContext` with typed Symbols to propagate state hierarchies securely down the component tree.
- Services exposing reactive state MUST provide explicit `create[Domain]Context()` and `use[Domain]Context()` accessors rather than exporting shared singleton instances.
- Components NEVER read from or write to un-encapsulated global module variables when executing on the server.
- Read-only immutable configurations at module root MUST be declared as plain TypeScript constants without reactive wrappers.

## Bad vs Good Implementations
### Module-Level Shared State vs Context-Isolated Request State in Svelte 5

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-level $state is instantiated once when the module loads into Node/V8 memory. On SSR, every concurrent HTTP request shares the exact same state object reference, leading to cross-tenant data exposure and unpredictable data races.
```typescript
// src/lib/stores/auth.svelte.ts
// ANTI-PATTERN: Module-level $state is a singleton across all concurrent SSR requests!
export interface UserProfile {
  id: string;
  tenantId: string;
  name: string;
}

// CRITICAL FLAW: Request A sets this proxy; Request B concurrent read leaks Tenant A data!
export const currentUserState = $state<{
  user: UserProfile | null;
  isAuthenticated: boolean;
}>({ user: null, isAuthenticated: false });

export function setUser(user: UserProfile): void {
  currentUserState.user = user;
  currentUserState.isAuthenticated = true;
}
```

#### Production Standard (Correct)
> **Standard**: Encapsulating $state inside a class coupled with Svelte's `setContext` and `getContext` ensures that each SSR request receives its own isolated instance bound to the request's component tree lifecycle, guaranteeing zero cross-request pollution.
```typescript
// src/lib/stores/auth.svelte.ts
import { getContext, setContext } from 'svelte';

export interface UserProfile {
  id: string;
  tenantId: string;
  name: string;
}

export class AuthStore {
  #user = $state<UserProfile | null>(null);
  #isAuthenticated = $derived(this.#user !== null);

  constructor(initialUser: UserProfile | null = null) {
    this.#user = initialUser;
  }

  get user(): UserProfile | null {
    return this.#user;
  }

  get isAuthenticated(): boolean {
    return this.#isAuthenticated;
  }

  setUser(user: UserProfile | null): void {
    this.#user = user;
  }
}

const AUTH_KEY = Symbol('AUTH_STORE_CONTEXT');

export function setAuthStore(initialUser: UserProfile | null = null): AuthStore {
  const store = new AuthStore(initialUser);
  return setContext(AUTH_KEY, store);
}

export function useAuthStore(): AuthStore {
  const store = getContext<AuthStore | undefined>(AUTH_KEY);
  if (!store) {
    throw new Error('useAuthStore must be called within an initialized component hierarchy context.');
  }
  return store;
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Svelte 5 Runes SSR Reactive Scope Isolation & Context Encapsulation

Svelte 5 Runes SSR Reactive Scope Isolation & Context Encapsulation defines an industrial-grade behavioral standard for frontend engineering. Enforces strict lexical and contextual isolation for Svelte 5 reactive runes in SSR environments. Module-level $state declarations share memory across concurrent requests in persistent Node.js/edge worker runtimes, causing critical cross-tenant data contamination and memory leaks. Mutable reactive proxies must strictly be encapsulated within request-scoped contexts, factory functions, or component instances. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Module-Level $state Declarations Causing Cross-Request State Pollution in SvelteKit SSR Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftModule-Level $state Declarations Causing Cross-Request State Pollution in SvelteKit SSRCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST NEVER declare mutable `$state` or `$state.raw` at the top level of `.svelte.ts` or `.svelte` modules evaluated during SSR.

Engineers MUST NEVER declare mutable `$state` or `$state.raw` at the top level of `.svelte.ts` or `.svelte` modules evaluated during SSR.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST encapsulate shared reactive domain logic within class instances or closures instantiated inside component lifecycles or SvelteKit request hooks.

Engineers MUST encapsulate shared reactive domain logic within class instances or closures instantiated inside component lifecycles or SvelteKit request hooks.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Code MUST use Svelte 5's `setContext` and `getContext` with typed Symbols to propagate state hierarchies securely down the component tree.

Code MUST use Svelte 5's `setContext` and `getContext` with typed Symbols to propagate state hierarchies securely down the component tree.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services exposing reactive state MUST provide explicit `create[Domain]Context()` and `use[Domain]Context()` accessors rather than exporting shared singleton instances.

Services exposing reactive state MUST provide explicit `create[Domain]Context()` and `use[Domain]Context()` accessors rather than exporting shared singleton instances.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER read from or write to un-encapsulated global module variables when executing on the server.

Components NEVER read from or write to un-encapsulated global module variables when executing on the server.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Read-only immutable configurations at module root MUST be declared as plain TypeScript constants without reactive wrappers.

Read-only immutable configurations at module root MUST be declared as plain TypeScript constants without reactive wrappers.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Svelte 5 Runes SSR Reactive Scope Isolation & Context Encapsulation critical for AI coding assistants?

Enforces strict lexical and contextual isolation for Svelte 5 reactive runes in SSR environments. Module-level $state declarations share memory across concurrent requests in persistent Node.js/edge worker runtimes, causing critical cross-tenant data contamination and memory leaks. Mutable reactive proxies must strictly be encapsulated within request-scoped contexts, factory functions, or component instances. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Module-Level $state Declarations Causing Cross-Request State Pollution in SvelteKit SSR) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Svelte