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-isolation-vite-6-environme-655

Strict Runtime Boundary and Module Graph Isolation in Vite 6 Environment API

Vite 6 introduces the Environment API to orchestrate disparate runtimes (e.g., client DOM, Node.js SSR, Edge Workers) within a unified dev server pipeline. When building multi-runtime systems, plugins and modules must strictly isolate their module graphs, transform hooks, and hot-module replacement (HMR) state to prevent runtime leaks, cross-environment variable bleeding, and server-side evaluation contamination during development and bundling.

Prohibited Anti-Pattern: Cross-Environment Module Graph Contamination and Shared Plugin Instance State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Runtime Boundary and Module Graph Isolation in Vite 6 Environment API - Vite 6 introduces the Environment API to orchestrate disparate runtimes (e.g., client DOM, Node.js SSR, Edge Workers) within a unified dev server pipeline. When building multi-runtime systems, plugins and modules must strictly isolate their module graphs, transform hooks, and hot-module replacement (HMR) state to prevent runtime leaks, cross-environment variable bleeding, and server-side evaluation contamination during development and bundling.
globs: vite.config.{ts,js,mjs}, plugins/**/*.{ts,js,mjs}, src/server/**/*.{ts,tsx,js,jsx}, src/client/**/*.{ts,tsx,js,jsx}, src/edge/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-environment-api-multi-runtime-isolation-vite-6-environme-655"
---

# Strict Runtime Boundary and Module Graph Isolation in Vite 6 Environment API

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Environment Module Graph Contamination and Shared Plugin Instance State

## System Constraints
You are a Principal Software Architect enforcing runtime boundary isolation in Vite 6 using the Environment API. You must ensure that code targeting distinct execution environments (client, node, workerd/edge) does not leak state, share unified module graph instances, cross-pollinate imports, or use legacy SSR flags in plugin hooks. Enforce environment-aware plugin design, strict isolation of dev server runtimes, and isolated HMR channel emission.

## Strict Guidelines
- Engineers MUST ALWAYS check `this.environment.name` in Vite plugin hooks (`resolveId`, `load`, `transform`) instead of relying on deprecated `options?.ssr` booleans.
- Engineers MUST NEVER access shared module-level state across environment transforms; store per-environment metadata explicitly inside `this.environment.pluginData` or dedicated Map keyed by `Environment` instances.
- Engineers MUST configure distinct environment runtime instances in `vite.config.ts` using `createRunnableDevEnvironment` or dedicated environment runtimes, ensuring `node` and `edge` do not share global node polyfills.
- Plugins MUST NOT emit HMR payloads using `server.ws.send` globally when the payload affects only a specific runtime boundary; dispatch strictly via `this.environment.hot.send`.
- Engineers MUST configure isolated `resolve.conditions` and `resolve.externalConditions` for each runtime environment in `vite.config.ts` to prevent node-only native C++ modules from resolving within edge/workerd graphs.

## Bad vs Good Implementations
### Migrating Plugin Hooks from Legacy SSR Flag to Vite 6 Environment API

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `options?.ssr` treats all non-client environments uniformly, failing to distinguish between Node.js and Edge targets. Additionally, shared closure cache (`globalTransformCache`) corrupts builds by returning Node-transformed code to Edge runtimes.
```typescript
import type { Plugin } from 'vite';

export function runtimeBoundaryPlugin(): Plugin {
  const globalTransformCache = new Map<string, string>();

  return {
    name: 'runtime-boundary-plugin',
    transform(code, id, options) {
      // BAD: Legacy boolean check does not distinguish between Node.js and Edge/workerd runtimes
      const isSsr = options?.ssr;
      if (isSsr) {
        // BAD: Shared cache across different SSR environments (e.g. Node vs Edge)
        if (globalTransformCache.has(id)) {
          return globalTransformCache.get(id);
        }
        const transformed = code.replace(/__RUNTIME_TARGET__/g, '"server"');
        globalTransformCache.set(id, transformed);
        return transformed;
      }
      return code.replace(/__RUNTIME_TARGET__/g, '"client"');
    }
  };
}
```

#### Production Standard (Correct)
> **Standard**: Leverages `this.environment.name` to explicitly target distinct environments (`edge`, `ssr`, `client`). Encapsulates cache scope using a `WeakMap` keyed on the Vite `Environment` instance to prevent module leakage.
```typescript
import type { Plugin, Environment } from 'vite';

export function runtimeBoundaryPlugin(): Plugin {
  // Invariant: Isolate cache per Environment instance
  const envCaches = new WeakMap<Environment, Map<string, string>>();

  return {
    name: 'runtime-boundary-plugin',
    // Enforce environment isolation in Vite 6
    transform(code, id) {
      const env = this.environment;
      if (!env) {
        throw new Error('This plugin requires Vite 6 with Environment API support.');
      }

      let cache = envCaches.get(env);
      if (!cache) {
        cache = new Map<string, string>();
        envCaches.set(env, cache);
      }

      if (cache.has(id)) {
        return cache.get(id);
      }

      // Explicitly branch behavior based on named environment target
      let transformed = code;
      if (env.name === 'edge') {
        transformed = code.replace(/__RUNTIME_TARGET__/g, '"edge-worker"');
      } else if (env.name === 'ssr') {
        transformed = code.replace(/__RUNTIME_TARGET__/g, '"node-server"');
      } else if (env.name === 'client') {
        transformed = code.replace(/__RUNTIME_TARGET__/g, '"browser"');
      }

      cache.set(id, transformed);
      return { code: transformed, map: null };
    }
  };
}
```

### Configuring Distinct Environment Module Resolution Boundaries in vite.config.ts

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring a single `ssr` target and shared `resolve.conditions` prevents separating Node-specific dependencies (like `fs`, `buffer`) from Edge environments (Workerd), leading to bundling collisions and missing runtime symbol crashes.
```typescript
import { defineConfig } from 'vite';

export default defineConfig({
  // BAD: Monolithic configuration with shared resolution conditions for both server and edge
  ssr: {
    target: 'node',
    noExternal: true,
  },
  resolve: {
    conditions: ['import', 'module', 'browser', 'node']
  }
});
```

#### Production Standard (Correct)
> **Standard**: Declares separate environment pipelines with explicit runtime conditions. The `edge` and `ssr` targets resolve mutually exclusive module entry points, ensuring zero boundary overlap during development and bundling.
```typescript
import { defineConfig } from 'vite';

export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client'
      }
    },
    ssr: {
      resolve: {
        conditions: ['node', 'import', 'module'],
        externalConditions: ['node']
      },
      build: {
        outDir: 'dist/server'
      }
    },
    edge: {
      resolve: {
        conditions: ['workerd', 'worker', 'edge-light', 'import'],
        externalConditions: ['workerd', 'worker']
      },
      build: {
        outDir: 'dist/edge'
      }
    }
  }
});
```

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: Strict Runtime Boundary and Module Graph Isolation in Vite 6 Environment API

Strict Runtime Boundary and Module Graph Isolation in Vite 6 Environment API defines an industrial-grade behavioral standard for frontend engineering. Vite 6 introduces the Environment API to orchestrate disparate runtimes (e.g., client DOM, Node.js SSR, Edge Workers) within a unified dev server pipeline. When building multi-runtime systems, plugins and modules must strictly isolate their module graphs, transform hooks, and hot-module replacement (HMR) state to prevent runtime leaks, cross-environment variable bleeding, and server-side evaluation contamination during development and bundling. 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-Environment Module Graph Contamination and Shared Plugin Instance State 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-Environment Module Graph Contamination and Shared Plugin Instance StateCritical
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 check `this.environment.name` in Vite plugin hooks (`resolveId`, `load`, `transform`) instead of relying on deprecated `options?.ssr` booleans.

Engineers MUST ALWAYS check `this.environment.name` in Vite plugin hooks (`resolveId`, `load`, `transform`) instead of relying on deprecated `options?.ssr` booleans.

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 NEVER access shared module-level state across environment transforms

Engineers MUST NEVER access shared module-level state across environment transforms; store per-environment metadata explicitly inside `this.environment.pluginData` or dedicated Map keyed by `Environment` instances.

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 configure distinct environment runtime instances in `vite.config.ts` using `createRunnableDevEnvironment` or dedicated environment runtimes, ensuring `node` and `edge` do not share global node polyfills.

Engineers MUST configure distinct environment runtime instances in `vite.config.ts` using `createRunnableDevEnvironment` or dedicated environment runtimes, ensuring `node` and `edge` do not share global node 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

Plugins MUST NOT emit HMR payloads using `server.ws.send` globally when the payload affects only a specific runtime boundary

Plugins MUST NOT emit HMR payloads using `server.ws.send` globally when the payload affects only a specific runtime boundary; dispatch strictly via `this.environment.hot.send`.

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 configure isolated `resolve.conditions` and `resolve.externalConditions` for each runtime environment in `vite.config.ts` to prevent node-only native C++ modules from resolving within edge/workerd graphs.

Engineers MUST configure isolated `resolve.conditions` and `resolve.externalConditions` for each runtime environment in `vite.config.ts` to prevent node-only native C++ modules from resolving within edge/workerd 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.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Strict Runtime Boundary and Module Graph Isolation in Vite 6 Environment API critical for AI coding assistants?

Vite 6 introduces the Environment API to orchestrate disparate runtimes (e.g., client DOM, Node.js SSR, Edge Workers) within a unified dev server pipeline. When building multi-runtime systems, plugins and modules must strictly isolate their module graphs, transform hooks, and hot-module replacement (HMR) state to prevent runtime leaks, cross-environment variable bleeding, and server-side evaluation contamination during development and bundling. 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-Environment Module Graph Contamination and Shared Plugin Instance State) 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

Strict