This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: vite-6-ssr-modulerunner-isolated-realm-cleanup

Vite 6 SSR ModuleRunner Isolated Realm Cleanup and Heap Invariant

Enforces deterministic heap boundary teardown, explicit runner destruction, and cross-request cache eviction when utilizing Vite 6 Environment API and ModuleRunner. Prevents cascading memory leaks and cross-tenant state pollution caused by lingering module evaluations, unevicted module caches, and orphaned evaluation contexts in long-running development and edge SSR runtimes.

Prohibited Anti-Pattern: Retaining persistent ModuleRunner instances across SSR request boundaries without realm teardown or explicit cache eviction.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 SSR ModuleRunner Isolated Realm Cleanup and Heap Invariant - Enforces deterministic heap boundary teardown, explicit runner destruction, and cross-request cache eviction when utilizing Vite 6 Environment API and ModuleRunner. Prevents cascading memory leaks and cross-tenant state pollution caused by lingering module evaluations, unevicted module caches, and orphaned evaluation contexts in long-running development and edge SSR runtimes.
globs: src/server/**/*.{ts,tsx}, server/**/*.{ts,tsx}, vite.config.{ts,js}, src/entry-server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-ssr-modulerunner-isolated-realm-cleanup"
---

# Vite 6 SSR ModuleRunner Isolated Realm Cleanup and Heap Invariant

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Retaining persistent ModuleRunner instances across SSR request boundaries without realm teardown or explicit cache eviction.

## System Constraints
You are a Principal Engineer enforcing Vite 6 SSR Module Runner Isolated Realm Cleanup Invariant. Mandate deterministic module cache eviction, explicit ModuleRunner lifecycle management, and strict isolation of V8 evaluation contexts across SSR request lifecycles. Prevent retained references in module evaluators and ensure process-level cleanups upon runtime teardown.

## Strict Guidelines
- Engineers MUST ALWAYS invoke `runner.close()` and `runner.clearCache()` within `finally` blocks or utilize deterministic scope disposal (`using` / `AsyncDisposable`) when handling scoped SSR evaluation cycles.
- Engineers MUST NOT cache evaluated SSR module namespaces across distinct execution contexts without an explicit cache-invalidation policy keyed to HMR updates via `environment.hot`.
- Code SHOULD rely on `environment.fetchModule` and custom `ModuleRunnerTransport` channels that explicitly sever circular object references upon transport completion.
- Services MUST ensure that custom `ModuleEvaluator` implementations clean up temporary evaluation scripts, source map caches, and detached DOM/Node global shims to avoid retaining entire V8 context boundaries.
- Components NEVER store request-specific tenant state, headers, or security tokens in module-level global variables evaluated by `ModuleRunner`, as instances may persist across executions within the same runner context.

## Bad vs Good Implementations
### ModuleRunner Lifecycle and Realm Teardown Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Reusing a single ModuleRunner instance indefinitely without explicit cache boundaries or eviction allows module-level state and evaluated closures to retain the outer heap. Over thousands of requests or HMR cycles, stale module graphs remain rooted in the evaluator registry, causing unbounded heap growth and cross-request state leakage.
```typescript
import { createServer } from 'vite';
import { ModuleRunner, ESModulesEvaluator } from 'vite/module-runner';

const vite = await createServer({ server: { middlewareMode: true }, appType: 'custom' });

// Anti-pattern: Global singleton runner accumulates module state and closures across requests
const runner = new ModuleRunner(
  {
    root: vite.config.root,
    transport: {
      invoke: async (payload) => vite.ssrFetchModule(payload.id, payload.importer),
    },
  },
  new ESModulesEvaluator()
);

export async function handleRequest(url: string, tenantId: string) {
  // Leaks memory: Module cache is never invalidated or bounded, cross-tenant state bleeds
  const entry = await runner.import('/src/entry-server.ts');
  return entry.render(url, { tenantId });
}
```

#### Production Standard (Correct)
> **Standard**: The good pattern bounds the evaluation lifecycle. By triggering runner.clearCache() and runner.close() in a guaranteed finally block, internal evaluator references and module graphs are dereferenced, allowing the V8 garbage collector to evict the isolated realm and eliminate heap bloat.
```typescript
import { createServer, type ViteDevServer } from 'vite';
import { ModuleRunner, ESModulesEvaluator } from 'vite/module-runner';

export class SsrRuntimeService {
  private constructor(private readonly vite: ViteDevServer) {}

  static async create(): Promise<SsrRuntimeService> {
    const vite = await createServer({
      server: { middlewareMode: true },
      appType: 'custom',
      environments: { ssr: {} }
    });
    return new SsrRuntimeService(vite);
  }

  async render(url: string, context: Record<string, unknown>): Promise<string> {
    const ssrEnv = this.vite.environments.ssr;
    
    // Invariant: Isolate evaluation context with deterministic lifecycle control
    const evaluator = new ESModulesEvaluator();
    const runner = new ModuleRunner(
      {
        root: this.vite.config.root,
        transport: {
          invoke: (payload) => ssrEnv.fetchModule(payload.id, payload.importer),
        },
      },
      evaluator
    );

    try {
      const entry = await runner.import<{ render: (u: string, c: unknown) => Promise<string> }>('/src/entry-server.ts');
      return await entry.render(url, context);
    } finally {
      // Invariant: Explicitly purge module cache and close the runner to detach V8 evaluation realms
      runner.clearCache();
      await runner.close();
    }
  }

  async destroy(): Promise<void> {
    await this.vite.close();
  }
}
```

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: Vite 6 SSR ModuleRunner Isolated Realm Cleanup and Heap Invariant

Vite 6 SSR ModuleRunner Isolated Realm Cleanup and Heap Invariant defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic heap boundary teardown, explicit runner destruction, and cross-request cache eviction when utilizing Vite 6 Environment API and ModuleRunner. Prevents cascading memory leaks and cross-tenant state pollution caused by lingering module evaluations, unevicted module caches, and orphaned evaluation contexts in long-running development and edge SSR runtimes. 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: Retaining persistent ModuleRunner instances across SSR request boundaries without realm teardown or explicit cache eviction. 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 DriftRetaining persistent ModuleRunner instances across SSR request boundaries without realm teardown or explicit cache eviction.Critical
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 ALWAYS invoke `runner.close()` and `runner.clearCache()` within `finally` blocks or utilize deterministic scope disposal (`using` / `AsyncDisposable`) when handling scoped SSR evaluation cycles.

Engineers MUST ALWAYS invoke `runner.close()` and `runner.clearCache()` within `finally` blocks or utilize deterministic scope disposal (`using` / `AsyncDisposable`) when handling scoped SSR evaluation cycles.

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 NOT cache evaluated SSR module namespaces across distinct execution contexts without an explicit cache-invalidation policy keyed to HMR updates via `environment.hot`.

Engineers MUST NOT cache evaluated SSR module namespaces across distinct execution contexts without an explicit cache-invalidation policy keyed to HMR updates via `environment.hot`.

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 SHOULD rely on `environment.fetchModule` and custom `ModuleRunnerTransport` channels that explicitly sever circular object references upon transport completion.

Code SHOULD rely on `environment.fetchModule` and custom `ModuleRunnerTransport` channels that explicitly sever circular object references upon transport completion.

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 MUST ensure that custom `ModuleEvaluator` implementations clean up temporary evaluation scripts, source map caches, and detached DOM/Node global shims to avoid retaining entire V8 context boundaries.

Services MUST ensure that custom `ModuleEvaluator` implementations clean up temporary evaluation scripts, source map caches, and detached DOM/Node global shims to avoid retaining entire V8 context boundaries.

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 store request-specific tenant state, headers, or security tokens in module-level global variables evaluated by `ModuleRunner`, as instances may persist across executions within the same runner context.

Components NEVER store request-specific tenant state, headers, or security tokens in module-level global variables evaluated by `ModuleRunner`, as instances may persist across executions within the same runner context.

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 Vite 6 SSR ModuleRunner Isolated Realm Cleanup and Heap Invariant critical for AI coding assistants?

Enforces deterministic heap boundary teardown, explicit runner destruction, and cross-request cache eviction when utilizing Vite 6 Environment API and ModuleRunner. Prevents cascading memory leaks and cross-tenant state pollution caused by lingering module evaluations, unevicted module caches, and orphaned evaluation contexts in long-running development and edge SSR runtimes. 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 (Retaining persistent ModuleRunner instances across SSR request boundaries without realm teardown or explicit cache eviction.) 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

Vite