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

Vite 6 Environment API Cross-Runtime Sandbox Isolation Standard

Enforces strict isolation across execution contexts (client, ssr, edge, and workerd) using the Vite 6 Environment API. Prevents module graph leakage, cross-environment global object bleeding, and build-time contamination across heterogenous SSR runtimes by mandating per-environment module runners and explicit condition exports.

Prohibited Anti-Pattern: Global Module Graph Leakage and Leaked Node.js Intrinsic Globals in Edge/Browser Bundles

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Cross-Runtime Sandbox Isolation Standard - Enforces strict isolation across execution contexts (client, ssr, edge, and workerd) using the Vite 6 Environment API. Prevents module graph leakage, cross-environment global object bleeding, and build-time contamination across heterogenous SSR runtimes by mandating per-environment module runners and explicit condition exports.
globs: vite.config.{ts,js,mjs}, src/entry.*.{ts,js}, src/server/**/*.{ts,js}, src/edge/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-environment-api-cross-runtime-isolation-vite-6-environme-285"
---

# Vite 6 Environment API Cross-Runtime Sandbox Isolation Standard

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Global Module Graph Leakage and Leaked Node.js Intrinsic Globals in Edge/Browser Bundles

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API Cross-Runtime Sandbox Isolation. Vite 6 deprecates monolithic `ssrLoadModule` in favor of per-environment runners and isolated Module Graphs. You must ensure that client, Node.js SSR, and Edge runtimes maintain strictly partitioned dependency graphs, export conditions, and global namespaces during dev and build phases.

## Strict Guidelines
- Engineers MUST ALWAYS configure distinct environments (e.g., `client`, `ssr`, `edge`) under `environments` within `vite.config.ts` rather than relying on legacy top-level `ssr` configurations.
- Engineers MUST instantiate separate `ModuleRunner` instances with custom `ESModulesEvaluator` or sandbox runners for non-Node.js target environments instead of executing code directly via Node VM globals.
- Engineers MUST NOT share in-memory cache singletons or cross-import runtime modules across environment boundaries (e.g., importing Node `fs` or `stream` into an edge runner or client entry).
- Build scripts MUST execute `builder.build(builder.environments[name])` individually per environment target rather than triggering unpartitioned simultaneous bundle outputs.
- Plugins MUST use `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) to restrict environment-specific transformations and prevent global leaks.

## Bad vs Good Implementations
### Vite 6 Isolated Environment Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using top-level `ssr` options pollutes the global module resolution logic, leaking Node.js globals and built-in modules into workerd/edge builds and preventing concurrent multi-runtime dev/build pipelines.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Vite 5 legacy SSR mixing edge and node resolution
export default defineConfig({
  ssr: {
    target: 'webworker',
    noExternal: true,
  },
  define: {
    'process.env.RUNTIME': JSON.stringify('edge'),
  },
});
```

#### Production Standard (Correct)
> **Standard**: Configuring explicit Vite 6 environments segregates module graphs, resolution condition sets, and build outputs, preventing cross-environment module pollution between Node and Edge.
```typescript
import { defineConfig } from 'vite';

// PRODUCTION INVARIANT: Vite 6 isolated Environment API
export default defineConfig({
  environments: {
    client: {
      consumer: 'client',
      build: { outDir: 'dist/client' },
    },
    ssr: {
      consumer: 'server',
      resolve: {
        conditions: ['node', 'import'],
        externalConditions: ['node'],
      },
      build: { outDir: 'dist/ssr' },
    },
    edge: {
      consumer: 'server',
      resolve: {
        conditions: ['worker', 'edge-routine', 'import'],
        noExternal: true,
      },
      build: {
        outDir: 'dist/edge',
        target: 'es2022',
      },
    },
  },
});
```

### Dev Server Runtime Execution via ModuleRunner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `vite.ssrLoadModule` forces execution through the default Node.js runtime environment, executing edge runtime code with unintended Node.js globals (e.g., `process`, `Buffer`).
```typescript
import { createServer } from 'vite';

// ANTI-PATTERN: Deprecated Vite 5 ssrLoadModule leaking Node VM globals
async function handleRequest(url: string) {
  const vite = await createServer();
  const entry = await vite.ssrLoadModule('/src/entry.edge.ts');
  return entry.render(url);
}
```

#### Production Standard (Correct)
> **Standard**: Using Vite 6's `createServerModuleRunner` scoped explicitly to `vite.environments.edge` guarantees that modules are evaluated strictly within the isolated evaluator context defined for edge runtimes.
```typescript
import { createServer } from 'vite';
import { createServerModuleRunner } from 'vite/module-runner';

// PRODUCTION INVARIANT: Partitioned ModuleRunner per isolated environment
async function handleRequest(url: string) {
  const vite = await createServer();
  const edgeEnvironment = vite.environments.edge;
  
  const runner = createServerModuleRunner(edgeEnvironment, {
    evaluator: edgeEnvironment.evaluator,
  });
  
  const entry = await runner.import('/src/entry.edge.ts');
  return entry.render(url);
}
```

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 Sandbox Isolation Standard

Vite 6 Environment API Cross-Runtime Sandbox Isolation Standard defines an industrial-grade behavioral standard for devops engineering. Enforces strict isolation across execution contexts (client, ssr, edge, and workerd) using the Vite 6 Environment API. Prevents module graph leakage, cross-environment global object bleeding, and build-time contamination across heterogenous SSR runtimes by mandating per-environment module runners and explicit condition exports. 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: Global Module Graph Leakage and Leaked Node.js Intrinsic Globals in Edge/Browser Bundles 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 DriftGlobal Module Graph Leakage and Leaked Node.js Intrinsic Globals in Edge/Browser BundlesCritical
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 environments (e.g., `client`, `ssr`, `edge`) under `environments` within `vite.config.ts` rather than relying on legacy top-level `ssr` configurations.

Engineers MUST ALWAYS configure distinct environments (e.g., `client`, `ssr`, `edge`) under `environments` within `vite.config.ts` rather than relying on legacy top-level `ssr` configurations.

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 instantiate separate `ModuleRunner` instances with custom `ESModulesEvaluator` or sandbox runners for non-Node.js target environments instead of executing code directly via Node VM globals.

Engineers MUST instantiate separate `ModuleRunner` instances with custom `ESModulesEvaluator` or sandbox runners for non-Node.js target environments instead of executing code directly via Node VM globals.

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 NOT share in-memory cache singletons or cross-import runtime modules across environment boundaries (e.g., importing Node `fs` or `stream` into an edge runner or client entry).

Engineers MUST NOT share in-memory cache singletons or cross-import runtime modules across environment boundaries (e.g., importing Node `fs` or `stream` into an edge runner or client entry).

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

Build scripts MUST execute `builder.build(builder.environments[name])` individually per environment target rather than triggering unpartitioned simultaneous bundle outputs.

Build scripts MUST execute `builder.build(builder.environments[name])` individually per environment target rather than triggering unpartitioned simultaneous bundle outputs.

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

Plugins MUST use `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) to restrict environment-specific transformations and prevent global leaks.

Plugins MUST use `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) to restrict environment-specific transformations and prevent global leaks.

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

Enforces strict isolation across execution contexts (client, ssr, edge, and workerd) using the Vite 6 Environment API. Prevents module graph leakage, cross-environment global object bleeding, and build-time contamination across heterogenous SSR runtimes by mandating per-environment module runners and explicit condition exports. 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 (Global Module Graph Leakage and Leaked Node.js Intrinsic Globals in Edge/Browser Bundles) 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