This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: vite-6-environment-api-multi-runtime-hermeticity

Vite 6 Environment API Multi-Runtime State Hermeticity Invariant

Vite 6 introduces multi-environment compilation (e.g., client, Node.js SSR, and Cloudflare Workerd/Edge) within a single pipeline. This invariant strictly enforces complete state and module hermeticity across concurrent runtimes and requests, prohibiting module-scope mutable singletons, enforcing `this.environment` context isolation in plugins, and securing request boundaries via runtime-native scoping like AsyncLocalStorage.

Prohibited Anti-Pattern: Cross-Request State Contamination and Runtime Pollution via Shared Singletons in Vite 6 Universal Builds

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime State Hermeticity Invariant - Vite 6 introduces multi-environment compilation (e.g., client, Node.js SSR, and Cloudflare Workerd/Edge) within a single pipeline. This invariant strictly enforces complete state and module hermeticity across concurrent runtimes and requests, prohibiting module-scope mutable singletons, enforcing `this.environment` context isolation in plugins, and securing request boundaries via runtime-native scoping like AsyncLocalStorage.
globs: vite.config.{ts,js,mjs}, src/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-environment-api-multi-runtime-hermeticity"
---

# Vite 6 Environment API Multi-Runtime State Hermeticity Invariant

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Contamination and Runtime Pollution via Shared Singletons in Vite 6 Universal Builds

## System Constraints
You are a Principal Software Architect enforcing the Vite 6 Environment API Multi-Runtime State Hermeticity Invariant. Vite 6 unifies compilation across distinct runtime environments (client, node, workerd, edge) concurrently. You must ensure absolute isolation: zero cross-environment plugin leaks, zero module-scope mutable state in universal SSR/Edge handlers, and proper scoping using Vite 6's Environment API (`this.environment`) instead of deprecated legacy flags.

## Strict Guidelines
- Engineers MUST ALWAYS inspect `this.environment.name` in Vite plugin hooks (`resolveId`, `load`, `transform`) rather than relying on legacy boolean flags like `options?.ssr`.
- Engineers MUST NOT declare mutable module-level state (`let currentRequest`, `const sessionCache = new Map()`) in SSR or Edge modules that persist across server requests.
- Engineers MUST scope request-bound singletons and telemetry contexts using runtime-safe context propagation (e.g., `AsyncLocalStorage` or explicit execution context injection).
- Vite configurations MUST define distinct `environments` configurations (`environments.client`, `environments.ssr`, `environments.edge`) with explicit resolution conditions and runner targets rather than mutating shared root options.
- Vite plugins MUST maintain separate internal metadata caches keyed by `environment.name` or leverage `this.environment` instance storage to prevent cross-runtime build artifact pollution.

## Bad vs Good Implementations
### Vite 6 Plugin Environment Context Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using top-level module variables in plugins pollutes state across concurrent Vite 6 environments (e.g., client, node SSR, and workerd). Relying on options.ssr ignores the multi-environment paradigm where multiple SSR targets can run concurrently.
```typescript
import type { Plugin } from 'vite';

// ANTI-PATTERN: Shared module-level state across environments & deprecated ssr flag
let sharedEnvironmentManifest: Record<string, string> = {};

export function universalManifestPlugin(): Plugin {
  return {
    name: 'universal-manifest',
    resolveId(id, importer, options) {
      // Legacy Vite 5 SSR flag check - misses specific target runtimes (workerd, node)
      const isSSR = Boolean(options?.ssr);
      if (id.startsWith('virtual:runtime-config')) {
        sharedEnvironmentManifest[id] = isSSR ? 'ssr-bundle' : 'client-bundle';
        return `\0${id}`;
      }
      return null;
    },
  };
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to Vite 6 Environment API standards by using this.environment to identify the runtime (client, ssr, workerd) and partitioning all internal plugin states hermetically with a WeakMap.
```typescript
import type { Plugin } from 'vite';

export function universalManifestPlugin(): Plugin {
  // Invariant: Scoped internal storage keyed by environment instance
  const environmentManifests = new WeakMap<object, Map<string, string>>();

  return {
    name: 'universal-manifest',
    resolveId(id) {
      if (!id.startsWith('virtual:runtime-config')) {
        return null;
      }
      // Invariant: Use this.environment to resolve target runtime context explicitly
      const currentEnv = this.environment;
      if (!environmentManifests.has(currentEnv)) {
        environmentManifests.set(currentEnv, new Map());
      }
      const manifest = environmentManifests.get(currentEnv)!;
      manifest.set(id, currentEnv.name);
      return `\0${id}?env=${currentEnv.name}`;
    },
  };
}
```

### Universal SSR/Edge Request Context Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Global module-scope variables are shared across all concurrent requests in Node.js and Edge runtime processes, leading to data bleeding and security vulnerabilities under concurrent load.
```typescript
import type { Request, Response } from 'express';

// ANTI-PATTERN: Module-level state shared across concurrent requests in long-lived server processes
let activeUserContext: { userId: string; role: string } | null = null;

export function setRequestContext(userId: string, role: string) {
  activeUserContext = { userId, role };
}

export function getRequestContext() {
  return activeUserContext;
}

export async function handleSSRRequest(req: Request, res: Response) {
  setRequestContext(req.headers['x-user-id'] as string, 'member');
  // Cross-request race condition: concurrent render can overwrite activeUserContext
  const renderedHtml = await renderApp();
  res.send(renderedHtml);
}
```

#### Production Standard (Correct)
> **Standard**: Uses AsyncLocalStorage to ensure strict hermetic isolation of per-request contexts across Node.js SSR and modern Edge runtimes, preventing cross-request data leaks.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';
import type { Request, Response } from 'express';

interface UserContext {
  readonly userId: string;
  readonly role: string;
}

// Invariant: AsyncLocalStorage guarantees hermetic state propagation per execution branch
const contextStore = new AsyncLocalStorage<UserContext>();

export function getRequestContext(): UserContext {
  const context = contextStore.getStore();
  if (!context) {
    throw new Error('RequestContext must be accessed within an active request execution frame');
  }
  return context;
}

export async function handleSSRRequest(req: Request, res: Response): Promise<void> {
  const userContext: UserContext = {
    userId: String(req.headers['x-user-id'] ?? 'anonymous'),
    role: 'member',
  };

  await contextStore.run(userContext, async () => {
    const renderedHtml = await renderApp();
    res.send(renderedHtml);
  });
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Vite 6 Environment API Multi-Runtime State Hermeticity Invariant

Vite 6 Environment API Multi-Runtime State Hermeticity Invariant defines an industrial-grade behavioral standard for frontend engineering. Vite 6 introduces multi-environment compilation (e.g., client, Node.js SSR, and Cloudflare Workerd/Edge) within a single pipeline. This invariant strictly enforces complete state and module hermeticity across concurrent runtimes and requests, prohibiting module-scope mutable singletons, enforcing `this.environment` context isolation in plugins, and securing request boundaries via runtime-native scoping like AsyncLocalStorage. 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: Cross-Request State Contamination and Runtime Pollution via Shared Singletons in Vite 6 Universal Builds 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 DriftCross-Request State Contamination and Runtime Pollution via Shared Singletons in Vite 6 Universal BuildsCritical
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 inspect `this.environment.name` in Vite plugin hooks (`resolveId`, `load`, `transform`) rather than relying on legacy boolean flags like `options?.ssr`.

Engineers MUST ALWAYS inspect `this.environment.name` in Vite plugin hooks (`resolveId`, `load`, `transform`) rather than relying on legacy boolean flags like `options?.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 NOT declare mutable module-level state (`let currentRequest`, `const sessionCache = new Map()`) in SSR or Edge modules that persist across server requests.

Engineers MUST NOT declare mutable module-level state (`let currentRequest`, `const sessionCache = new Map()`) in SSR or Edge modules that persist across server requests.

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

Engineers MUST scope request-bound singletons and telemetry contexts using runtime-safe context propagation (e.g., `AsyncLocalStorage` or explicit execution context injection).

Engineers MUST scope request-bound singletons and telemetry contexts using runtime-safe context propagation (e.g., `AsyncLocalStorage` or explicit execution context injection).

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

Vite configurations MUST define distinct `environments` configurations (`environments.client`, `environments.ssr`, `environments.edge`) with explicit resolution conditions and runner targets rather than mutating shared root options.

Vite configurations MUST define distinct `environments` configurations (`environments.client`, `environments.ssr`, `environments.edge`) with explicit resolution conditions and runner targets rather than mutating shared root options.

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

Vite plugins MUST maintain separate internal metadata caches keyed by `environment.name` or leverage `this.environment` instance storage to prevent cross-runtime build artifact pollution.

Vite plugins MUST maintain separate internal metadata caches keyed by `environment.name` or leverage `this.environment` instance storage to prevent cross-runtime build artifact pollution.

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 Environment API Multi-Runtime State Hermeticity Invariant critical for AI coding assistants?

Vite 6 introduces multi-environment compilation (e.g., client, Node.js SSR, and Cloudflare Workerd/Edge) within a single pipeline. This invariant strictly enforces complete state and module hermeticity across concurrent runtimes and requests, prohibiting module-scope mutable singletons, enforcing `this.environment` context isolation in plugins, and securing request boundaries via runtime-native scoping like AsyncLocalStorage. 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 (Cross-Request State Contamination and Runtime Pollution via Shared Singletons in Vite 6 Universal Builds) 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