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

Vite 6 Environment API Cross-Runtime Module Isolation Standard

Enforces strict module execution boundaries across heterogeneous execution targets (Client, Node SSR, and Edge Workers) using Vite 6's Environment API. Prevents cross-environment memory leaks, shared runtime state bleed, and unsafe module graph contamination in unified multi-target builds.

Prohibited Anti-Pattern: Shared Ambient Singletons and Unscoped Plugins Leaking Across DevEnvironment Boundaries

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 module execution boundaries across heterogeneous execution targets (Client, Node SSR, and Edge Workers) using Vite 6's Environment API. Prevents cross-environment memory leaks, shared runtime state bleed, and unsafe module graph contamination in unified multi-target builds.
globs: vite.config.ts, vite.config.*.ts, 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-runtime-isolation"
---

# Vite 6 Environment API Cross-Runtime Module Isolation Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Shared Ambient Singletons and Unscoped Plugins Leaking Across DevEnvironment Boundaries

## System Constraints
You are a Principal Engineer enforcing Vite 6 Environment API Cross-Runtime Module Isolation. You must mandate strict environment boundary partitioning in multi-target Vite configurations, ensuring 'client', 'ssr', and custom edge worker environments maintain completely isolated module graphs, separate transform caches, and zero shared module-level state. Reject legacy Vite 5 SSR patterns that share plugins or state caches across runtimes.

## Strict Guidelines
- Engineers MUST ALWAYS configure distinct environments under the Vite 6 `environments` configuration block (e.g., `client`, `ssr`, `edge`) with environment-specific `resolve.conditions`, `build.outDir`, and isolated module graphs.
- Engineers MUST NOT maintain shared mutable module-level singletons or caches across runtime boundaries; all request-scoped state MUST be passed via explicit execution context or environment-isolated stores.
- Vite plugins MUST target specific environments via the `applyToEnvironment(env)` hook or per-environment configuration blocks instead of executing uniform transforms across disparate module graphs.
- Edge worker modules MUST NOT import from Node.js runtime entry points or rely on client-side global object stubs (`window`, `document`) that compromise edge isolation.
- Engineers MUST utilize the Vite 6 `DevEnvironment` runner (`createViteRuntime` or `runner.executeEntrypoint`) instead of deprecated `viteDevServer.ssrLoadModule` to prevent Node-to-worker runtime memory leakage.

## Bad vs Good Implementations
### Configuring Multi-Environment Boundaries in Vite 6

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring a single target with top-level SSR settings causes client and worker module graphs to collide. Stateful plugins operate globally across all files, allowing edge-targeted transforms to taint client-bound bundles and producing cross-runtime memory leaks in development.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Legacy Vite 5 shared SSR setup causing graph crossover
export default defineConfig({
  build: {
    ssr: true,
    outDir: 'dist/server',
  },
  ssr: {
    target: 'webworker', // Pollutes entire build; client and edge share conditions
    noExternal: true,
  },
  plugins: [
    // Shared plugin instance maintaining global state across client & worker transforms
    {
      name: 'leaky-stateful-cache',
      transform(code, id) {
        // Unscoped cache shared across runtimes causes cross-env contamination
        return code;
      },
    },
  ],
});
```

#### Production Standard (Correct)
> **Standard**: Defines discrete execution runtimes using Vite 6's `environments` map. Resolution conditions, output directories, and plugin scopes are segregated per environment, preventing worker transforms and Node-specific modules from leaking into client or server bundles.
```typescript
import { defineConfig } from 'vite';

// PRODUCTION FIX: Vite 6 isolated Environment API definitions
export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client',
      },
      resolve: {
        conditions: ['browser', 'import'],
      },
    },
    edge: {
      build: {
        outDir: 'dist/edge',
      },
      resolve: {
        conditions: ['worker', 'edge-routine', 'import'],
      },
      consumer: 'server',
    },
    ssr: {
      build: {
        outDir: 'dist/ssr',
      },
      resolve: {
        conditions: ['node', 'import'],
      },
      consumer: 'server',
    },
  },
  plugins: [
    {
      name: 'isolated-env-plugin',
      applyToEnvironment(environment) {
        // Only attach transform pipeline to the specific execution context
        return environment.name === 'edge';
      },
      transform(code, id) {
        return code;
      },
    },
  ],
});
```

### Runtime Entry Point Execution with DevEnvironment

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy ssrLoadModule evaluates edge worker code within the host Node.js process environment, corrupting isolated edge primitives, preventing true worker runtime isolation, and persisting unbounded module-level memory in dev mode.
```typescript
import { ViteDevServer } from 'vite';

// ANTI-PATTERN: Using ssrLoadModule across mixed runtimes
export async function handleRequest(server: ViteDevServer, url: string) {
  // ssrLoadModule forces Node vm context even for worker-targeted modules,
  // leaking Node globals and module caches across invocations
  const entry = await server.ssrLoadModule('/src/entry.edge.ts');
  return entry.default.fetch(new Request(url));
}
```

#### Production Standard (Correct)
> **Standard**: Accessing the specific DevEnvironment ('edge') and executing code via its dedicated ModuleRunner ensures execution occurs in an isolated module graph with strict runtime isolation, clean teardown, and environment-accurate resolution.
```typescript
import { ViteDevServer } from 'vite';

// PRODUCTION FIX: Execute via Vite 6 isolated DevEnvironment
export async function handleRequest(server: ViteDevServer, url: string) {
  const edgeEnv = server.environments.edge;
  if (!edgeEnv) {
    throw new Error('Edge environment not configured on Vite server.');
  }

  // Use Vite 6 Runner bound strictly to the isolated edge environment module graph
  const edgeRunner = edgeEnv.runner;
  const entry = await edgeRunner.executeEntrypoint('/src/entry.edge.ts');
  
  return entry.default.fetch(new Request(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 Module Isolation Standard

Vite 6 Environment API Cross-Runtime Module Isolation Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict module execution boundaries across heterogeneous execution targets (Client, Node SSR, and Edge Workers) using Vite 6's Environment API. Prevents cross-environment memory leaks, shared runtime state bleed, and unsafe module graph contamination in unified multi-target builds. 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 Ambient Singletons and Unscoped Plugins Leaking Across DevEnvironment Boundaries 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 Ambient Singletons and Unscoped Plugins Leaking Across DevEnvironment BoundariesCritical
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 under the Vite 6 `environments` configuration block (e.g., `client`, `ssr`, `edge`) with environment-specific `resolve.conditions`, `build.outDir`, and isolated module graphs.

Engineers MUST ALWAYS configure distinct environments under the Vite 6 `environments` configuration block (e.g., `client`, `ssr`, `edge`) with environment-specific `resolve.conditions`, `build.outDir`, and isolated module graphs.

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 maintain shared mutable module-level singletons or caches across runtime boundaries

Engineers MUST NOT maintain shared mutable module-level singletons or caches across runtime boundaries; all request-scoped state MUST be passed via explicit execution context or environment-isolated stores.

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

Vite plugins MUST target specific environments via the `applyToEnvironment(env)` hook or per-environment configuration blocks instead of executing uniform transforms across disparate module graphs.

Vite plugins MUST target specific environments via the `applyToEnvironment(env)` hook or per-environment configuration blocks instead of executing uniform transforms across disparate module graphs.

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

Edge worker modules MUST NOT import from Node.js runtime entry points or rely on client-side global object stubs (`window`, `document`) that compromise edge isolation.

Edge worker modules MUST NOT import from Node.js runtime entry points or rely on client-side global object stubs (`window`, `document`) that compromise edge isolation.

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

Engineers MUST utilize the Vite 6 `DevEnvironment` runner (`createViteRuntime` or `runner.executeEntrypoint`) instead of deprecated `viteDevServer.ssrLoadModule` to prevent Node-to-worker runtime memory leakage.

Engineers MUST utilize the Vite 6 `DevEnvironment` runner (`createViteRuntime` or `runner.executeEntrypoint`) instead of deprecated `viteDevServer.ssrLoadModule` to prevent Node-to-worker runtime memory leakage.

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 module execution boundaries across heterogeneous execution targets (Client, Node SSR, and Edge Workers) using Vite 6's Environment API. Prevents cross-environment memory leaks, shared runtime state bleed, and unsafe module graph contamination in unified multi-target builds. 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 Ambient Singletons and Unscoped Plugins Leaking Across DevEnvironment Boundaries) 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