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

Vite 6 Environment API Heterogeneous Runtime Isolation & Graph Sandboxing

Enforces strict module graph separation, dedicated condition resolution, and isolated runtime symbol contexts when compiling heterogeneous targets (Node.js, Workerd, Deno) via Vite 6's Environment API. Prevents runtime symbol cross-contamination, illegal intrinsic leakage, and shared cache corruption across disparate deployment runtimes in unified pipelines.

Prohibited Anti-Pattern: Cross-Runtime Module Graph Pollution and Shared Resolver State in Multi-Environment Vite Pipelines

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Heterogeneous Runtime Isolation & Graph Sandboxing - Enforces strict module graph separation, dedicated condition resolution, and isolated runtime symbol contexts when compiling heterogeneous targets (Node.js, Workerd, Deno) via Vite 6's Environment API. Prevents runtime symbol cross-contamination, illegal intrinsic leakage, and shared cache corruption across disparate deployment runtimes in unified pipelines.
globs: vite.config.{ts,js,mjs}, plugins/**/*.{ts,js,mjs}, build/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-environment-api-runtime-isolation-vite-6-environme-540"
---

# Vite 6 Environment API Heterogeneous Runtime Isolation & Graph Sandboxing

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Cross-Runtime Module Graph Pollution and Shared Resolver State in Multi-Environment Vite Pipelines

## System Constraints
You are a Principal Software Architect enforcing runtime module graph isolation via the Vite 6 Environment API. You must ensure heterogeneous target architectures (e.g., Cloudflare Workerd, Node.js, Deno) maintain non-overlapping dependency resolution contexts, runtime conditions, and symbol boundaries within unified build configurations.

## Strict Guidelines
- Engineers MUST ALWAYS define isolated environments using the Vite 6 `environments` configuration block with explicit runtime targets (e.g., `environments.edge` and `environments.ssr`).
- Engineers MUST NOT rely on monolithic SSR flags or unified module graphs (`server.moduleGraph`) when compiling for divergent runtimes in the same pipeline.
- Plugins MUST inspect `this.environment.name` inside environment-aware lifecycle hooks (`resolveId`, `load`, `transform`) to branch runtime-specific virtual modules and polyfills.
- Engineers MUST enforce runtime-specific `resolve.conditions` per environment (e.g., `conditions: ['workerd', 'worker']` for edge vs `conditions: ['node']` for Node.js).
- Unified build orchestrations MUST use Vite 6 `builder.build(environment)` passes sequentially or safely in parallel without shared mutable plugin state.

## Bad vs Good Implementations
### Configuring Sandboxed Multi-Runtime Compilation Graphs in Vite 6

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This configuration uses legacy monolithic SSR settings, causing Cloudflare Workerd or Deno builds to pull in Node.js-specific symbols (`node:async_hooks`). The plugin hook lacks environment awareness, corrupting the shared resolution graph.
```typescript
import { defineConfig, type Plugin } from 'vite';

// ANTI-PATTERN: Leaks Node.js modules into edge runtimes through global plugin state
// and monolithic SSR configuration without Vite 6 Environment isolation.
export default defineConfig({
  ssr: {
    target: 'node',
    noExternal: true,
  },
  plugins: [{
    name: 'runtime-resolver',
    resolveId(source) {
      if (source === 'virtual:runtime-adapter') {
        // Unsandboxed: Resolves Node.js builtin unconditionally for all build targets
        return '\0node:async_hooks';
      }
      return null;
    }
  }]
});
```

#### Production Standard (Correct)
> **Standard**: Leverages the Vite 6 Environment API to isolate ModuleGraphs via `environments.edge` and `environments.node`. The custom plugin accesses `this.environment.name` in `resolveId`, ensuring Node.js native intrinsics never resolve into edge environments.
```typescript
import { defineConfig, type Plugin } from 'vite';

export default defineConfig({
  // Vite 6 Environment API: Sandboxed compilation graphs
  environments: {
    edge: {
      resolve: {
        conditions: ['workerd', 'worker', 'browser'],
        noExternal: true,
      },
      build: {
        outDir: 'dist/edge',
        rollupOptions: {
          input: 'src/entry.edge.ts',
        },
      },
    },
    node: {
      resolve: {
        conditions: ['node', 'import'],
        external: [/^node:/],
      },
      build: {
        outDir: 'dist/node',
        rollupOptions: {
          input: 'src/entry.node.ts',
        },
      },
    },
  },
  plugins: [{
    name: 'sandboxed-runtime-resolver',
    resolveId(source) {
      if (source === 'virtual:runtime-adapter') {
        // Scope resolution strictly to the executing Vite 6 environment
        if (this.environment.name === 'edge') {
          return '\0virtual:edge-adapter';
        }
        if (this.environment.name === 'node') {
          return '\0virtual:node-adapter';
        }
      }
      return null;
    },
    load(id) {
      if (id === '\0virtual:edge-adapter') {
        return 'export const runtime = "workerd"; export const storage = new Map();';
      }
      if (id === '\0virtual:node-adapter') {
        return 'import { AsyncLocalStorage } from "node:async_hooks"; export const runtime = "node"; export const storage = new AsyncLocalStorage();';
      }
      return null;
    },
  } as Plugin],
});
```

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 Heterogeneous Runtime Isolation & Graph Sandboxing

Vite 6 Environment API Heterogeneous Runtime Isolation & Graph Sandboxing defines an industrial-grade behavioral standard for devops engineering. Enforces strict module graph separation, dedicated condition resolution, and isolated runtime symbol contexts when compiling heterogeneous targets (Node.js, Workerd, Deno) via Vite 6's Environment API. Prevents runtime symbol cross-contamination, illegal intrinsic leakage, and shared cache corruption across disparate deployment runtimes in unified pipelines. 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-Runtime Module Graph Pollution and Shared Resolver State in Multi-Environment Vite Pipelines 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-Runtime Module Graph Pollution and Shared Resolver State in Multi-Environment Vite PipelinesCritical
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 define isolated environments using the Vite 6 `environments` configuration block with explicit runtime targets (e.g., `environments.edge` and `environments.ssr`).

Engineers MUST ALWAYS define isolated environments using the Vite 6 `environments` configuration block with explicit runtime targets (e.g., `environments.edge` and `environments.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 rely on monolithic SSR flags or unified module graphs (`server.moduleGraph`) when compiling for divergent runtimes in the same pipeline.

Engineers MUST NOT rely on monolithic SSR flags or unified module graphs (`server.moduleGraph`) when compiling for divergent runtimes in the same pipeline.

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

Plugins MUST inspect `this.environment.name` inside environment-aware lifecycle hooks (`resolveId`, `load`, `transform`) to branch runtime-specific virtual modules and polyfills.

Plugins MUST inspect `this.environment.name` inside environment-aware lifecycle hooks (`resolveId`, `load`, `transform`) to branch runtime-specific virtual modules and polyfills.

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

Engineers MUST enforce runtime-specific `resolve.conditions` per environment (e.g., `conditions

Engineers MUST enforce runtime-specific `resolve.conditions` per environment (e.g., `conditions: ['workerd', 'worker']` for edge vs `conditions: ['node']` for Node.js).

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

Unified build orchestrations MUST use Vite 6 `builder.build(environment)` passes sequentially or safely in parallel without shared mutable plugin state.

Unified build orchestrations MUST use Vite 6 `builder.build(environment)` passes sequentially or safely in parallel without shared mutable plugin state.

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 Heterogeneous Runtime Isolation & Graph Sandboxing critical for AI coding assistants?

Enforces strict module graph separation, dedicated condition resolution, and isolated runtime symbol contexts when compiling heterogeneous targets (Node.js, Workerd, Deno) via Vite 6's Environment API. Prevents runtime symbol cross-contamination, illegal intrinsic leakage, and shared cache corruption across disparate deployment runtimes in unified pipelines. 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-Runtime Module Graph Pollution and Shared Resolver State in Multi-Environment Vite Pipelines) 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.

1 Rule in Stack

Vite