This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: vite6-cross-runtime-environment-isolation-standard

Vite 6 Environment API Cross-Runtime Module Isolation Standard

Enforces strict memory, global scope, and module graph isolation when simultaneously executing client, edge-worker (WinterCG), and Node.js runtimes in Vite 6 pipelines. Prevents cross-runtime state leakage, unisolated global mutations, and corrupted Hot Module Replacement (HMR) broadcasts across environment boundaries.

Prohibited Anti-Pattern: Shared Module Graph Contamination and Global Scope Bleed Across Vite 6 Multi-Runtime Environments

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Cross-Runtime Module Isolation Standard - Enforces strict memory, global scope, and module graph isolation when simultaneously executing client, edge-worker (WinterCG), and Node.js runtimes in Vite 6 pipelines. Prevents cross-runtime state leakage, unisolated global mutations, and corrupted Hot Module Replacement (HMR) broadcasts across environment boundaries.
globs: vite.config.{ts,js,mjs}, src/**/*.{ts,tsx,js,jsx}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-cross-runtime-environment-isolation-standard"
---

# Vite 6 Environment API Cross-Runtime Module Isolation Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Shared Module Graph Contamination and Global Scope Bleed Across Vite 6 Multi-Runtime Environments

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API standards. Vite 6 introduces distinct `Environment` instances (e.g., client, ssr, edge/workerd) to supersede legacy monolithic SSR transforms. You must mandate strict isolation of module graphs, runtime conditions, and HMR communication channels. Never allow direct cross-runtime imports, mutable global scope pollution across workers and Node threads, or broadcast HMR messaging that treats all runtime targets identically.

## Strict Guidelines
- Engineers MUST ALWAYS configure distinct runtimes within `environments.<name>` using dedicated `resolve.conditions`, module runners, and runtime targets rather than legacy root-level SSR overrides.
- Engineers MUST NOT mutate `globalThis` or attach runtime-specific primitives (e.g., Node's `Buffer` or `process.env`, WinterCG `Request`/`Response`, browser `window`) to universal shared modules.
- Code SHOULD utilize Vite 6's `environment.hot.send` and `environment.hot.on` to isolate HMR communication per runtime instead of broadcasting across the universal `server.ws` channel.
- Services MUST enforce isolated `moduleGraph` boundaries by accessing `server.environments[name].moduleGraph` rather than the deprecated top-level `server.moduleGraph`.
- Components NEVER import server-only or edge-only modules into shared execution paths without explicit export conditions defined in `package.json` or explicit Vite environment separation.

## Bad vs Good Implementations
### Configuring Vite 6 Isolated Environments vs Legacy Shared SSR

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring runtimes via legacy root-level `ssr` configurations causes module graph collision between Node.js, Web Workers, and client builds. Global `server.ws.send` contaminates distinct runtime event loops with unfilterable payloads.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Vite 5 legacy multi-runtime sharing a single root module graph
// and broadcasting HMR globally across incompatible runtimes.
export default defineConfig({
  ssr: {
    target: 'webworker',
    noExternal: true,
  },
  plugins: [{
    name: 'cross-runtime-leak',
    handleHotUpdate({ server, modules }) {
      // Broadcasts to all clients, Node SSR, and Edge workers indiscriminately
      server.ws.send({ type: 'custom', event: 'reload' });
      return modules;
    }
  }]
});
```

#### Production Standard (Correct)
> **Standard**: Explicitly segregates `client`, `ssr`, and `edge` into independent `Environment` configurations with dedicated export conditions (`node` vs `worker`). HMR updates are cleanly isolated per environment using Vite 6 `hotUpdate` and `environment.hot`.
```typescript
import { defineConfig } from 'vite';

// PRODUCTION INVARIANT: Vite 6 Environment API with isolated module graphs,
// dedicated runtime conditions, and environment-scoped HMR.
export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client'
      }
    },
    ssr: {
      resolve: {
        conditions: ['node', 'import']
      },
      build: {
        outDir: 'dist/ssr'
      }
    },
    edge: {
      resolve: {
        conditions: ['worker', 'workerd', 'browser'],
        noExternal: true
      },
      build: {
        outDir: 'dist/edge'
      }
    }
  },
  plugins: [{
    name: 'environment-isolated-hmr',
    hotUpdate({ environment, modules }) {
      // Isolated HMR targeting strictly the originating runtime
      environment.hot.send({
        type: 'custom',
        event: `${environment.name}:update`,
        data: { paths: modules.map(m => m.url) }
      });
      return modules;
    }
  }]
});
```

### Runtime-Safe Environment State Access vs Leaking Global State

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating `globalThis` creates memory leaks and cross-contamination when evaluating multiple runtime targets in the same dev process. Node's `process.env` is accessed unconditionally, causing runtime panics in Edge and Browser contexts.
```typescript
// ANTI-PATTERN: Shared global mutation polluting cross-environment memory
declare global {
  var __runtimeSession: { id: string } | undefined;
}

export function getSessionId(): string {
  if (!globalThis.__runtimeSession) {
    // Node, Edge-worker, and Client will corrupt this shared mutable singleton
    globalThis.__runtimeSession = { id: (process.env.SESSION_ID as string) };
  }
  return globalThis.__runtimeSession.id;
}
```

#### Production Standard (Correct)
> **Standard**: Enforces execution boundaries using `import.meta.env.SSR` and runtime-safe memory isolation primitives (`AsyncLocalStorage`), eliminating mutable cross-runtime leaks across `globalThis`.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

interface SessionContext {
  readonly id: string;
}

// PRODUCTION INVARIANT: Runtime-isolated contextual storage
const nodeStorage = new AsyncLocalStorage<SessionContext>();

export function runWithSession<T>(id: string, fn: () => T): T {
  if (import.meta.env.SSR) {
    return nodeStorage.run({ id }, fn);
  }
  throw new Error('runWithSession is restricted to isolated server environments');
}

export function getSessionId(): string {
  if (import.meta.env.SSR) {
    const session = nodeStorage.getStore();
    if (!session) throw new Error('No active runtime session found');
    return session.id;
  }
  throw new Error('Direct session access prohibited in client environment');
}
```

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 Environment API Cross-Runtime Module Isolation Standard

Vite 6 Environment API Cross-Runtime Module Isolation Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict memory, global scope, and module graph isolation when simultaneously executing client, edge-worker (WinterCG), and Node.js runtimes in Vite 6 pipelines. Prevents cross-runtime state leakage, unisolated global mutations, and corrupted Hot Module Replacement (HMR) broadcasts across environment boundaries. 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: Shared Module Graph Contamination and Global Scope Bleed Across Vite 6 Multi-Runtime Environments 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 DriftShared Module Graph Contamination and Global Scope Bleed Across Vite 6 Multi-Runtime EnvironmentsCritical
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 configure distinct runtimes within `environments.<name>` using dedicated `resolve.conditions`, module runners, and runtime targets rather than legacy root-level SSR overrides.

Engineers MUST ALWAYS configure distinct runtimes within `environments.<name>` using dedicated `resolve.conditions`, module runners, and runtime targets rather than legacy root-level SSR overrides.

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 mutate `globalThis` or attach runtime-specific primitives (e.g., Node's `Buffer` or `process.env`, WinterCG `Request`/`Response`, browser `window`) to universal shared modules.

Engineers MUST NOT mutate `globalThis` or attach runtime-specific primitives (e.g., Node's `Buffer` or `process.env`, WinterCG `Request`/`Response`, browser `window`) to universal shared modules.

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 utilize Vite 6's `environment.hot.send` and `environment.hot.on` to isolate HMR communication per runtime instead of broadcasting across the universal `server.ws` channel.

Code SHOULD utilize Vite 6's `environment.hot.send` and `environment.hot.on` to isolate HMR communication per runtime instead of broadcasting across the universal `server.ws` channel.

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 enforce isolated `moduleGraph` boundaries by accessing `server.environments[name].moduleGraph` rather than the deprecated top-level `server.moduleGraph`.

Services MUST enforce isolated `moduleGraph` boundaries by accessing `server.environments[name].moduleGraph` rather than the deprecated top-level `server.moduleGraph`.

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 import server-only or edge-only modules into shared execution paths without explicit export conditions defined in `package.json` or explicit Vite environment separation.

Components NEVER import server-only or edge-only modules into shared execution paths without explicit export conditions defined in `package.json` or explicit Vite environment separation.

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 Cross-Runtime Module Isolation Standard critical for AI coding assistants?

Enforces strict memory, global scope, and module graph isolation when simultaneously executing client, edge-worker (WinterCG), and Node.js runtimes in Vite 6 pipelines. Prevents cross-runtime state leakage, unisolated global mutations, and corrupted Hot Module Replacement (HMR) broadcasts across environment boundaries. 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 (Shared Module Graph Contamination and Global Scope Bleed Across Vite 6 Multi-Runtime Environments) 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