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

Vite 6 Environment API Multi-Runtime Module Isolation Invariant

Enforces complete memory, module graph, and execution isolation across compilation targets (client, edge/workerd, node) via the Vite 6 Environment API. Prevents cross-runtime prototype pollution, server secret leakage into client bundles, and broken transform caches caused by shared plugin state. Deprecates legacy monolithic SSR primitives in favor of per-environment module runners and isolated graph invalidation.

Prohibited Anti-Pattern: Leaking Shared Plugin State and Cross-Executing Code Across Vite Runtime Environments

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime Module Isolation Invariant - Enforces complete memory, module graph, and execution isolation across compilation targets (client, edge/workerd, node) via the Vite 6 Environment API. Prevents cross-runtime prototype pollution, server secret leakage into client bundles, and broken transform caches caused by shared plugin state. Deprecates legacy monolithic SSR primitives in favor of per-environment module runners and isolated graph invalidation.
globs: vite.config.{ts,js,mjs}, plugins/**/*.{ts,js}, src/**/*.{ts,tsx}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-module-isolation-standard"
---

# Vite 6 Environment API Multi-Runtime Module Isolation Invariant

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Leaking Shared Plugin State and Cross-Executing Code Across Vite Runtime Environments

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API Multi-Runtime Module Isolation invariants. You must mandate strict structural boundaries across distinct execution runtimes (client, node, workerd/edge). You must reject legacy Vite SSR patterns such as `server.ssrLoadModule` or untargeted plugin transforms that pollute compilation environments.

## Strict Guidelines
- Engineers MUST ALWAYS scope plugin transform hooks, caches, and metadata to specific runtime environments using `this.environment.name` or `this.environment.mode`.
- Engineers MUST NOT maintain shared mutable singleton state in Vite plugin closures across multiple environments.
- Engineers MUST use `server.environments[name].runner.executeId()` instead of the legacy `server.ssrLoadModule()` when evaluating modules dynamically across heterogeneous runtimes.
- Engineers MUST target Hot Module Replacement (HMR) and module invalidation exclusively to the corresponding runtime module graph via `this.environment.moduleGraph` or `server.environments[name].moduleGraph`.
- Plugins targeting multiple environments MUST use the Vite 6 `perEnvironmentPlugin` API or branch logic explicitly per `Environment` instance to prevent Node-specific polyfills from leaking into Edge or Client graphs.
- Components and application code NEVER import from environment-restricted entrypoints without conditional package exports or environment-specific module resolution guards.

## Bad vs Good Implementations
### Vite Plugin Environment Isolation: Shared Cache vs Environment-Scoped Cache

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The plugin maintains a single in-memory Map shared across all environments and transforms modules without checking `this.environment`. This causes client bundles to receive server secrets (`DATABASE_URL`) and leads to cross-runtime cache collisions where client builds resolve Node-specific targets.
```typescript
import { Plugin } from 'vite';

// ANTI-PATTERN: Shared global state across client, edge, and node compilation
const resolvedModuleCache = new Map<string, string>();

export function leakyRuntimePlugin(): Plugin {
  return {
    name: 'leaky-runtime-plugin',
    resolveId(id) {
      // Shared cache cross-contaminates node and client module resolutions
      if (resolvedModuleCache.has(id)) {
        return resolvedModuleCache.get(id);
      }
      if (id === 'virtual:runtime-config') {
        const resolved = process.env.NODE_ENV === 'production' ? 'node-entry' : 'client-entry';
        resolvedModuleCache.set(id, resolved);
        return resolved;
      }
    },
    transform(code, id) {
      // Fails to inspect runtime environment; executes Node logic in client/edge context
      if (id.includes('runtime-config')) {
        return `export const secret = '${process.env.DATABASE_URL}';`;
      }
    }
  };
}
```

#### Production Standard (Correct)
> **Standard**: Uses Vite 6 `this.environment` and a `WeakMap` scoped to each `DevEnvironment` instance. Guarantees that Node and Client module resolutions never cross-pollinate, prevents secret leakage, and properly supports garbage collection on environment teardown.
```typescript
import { Plugin, DevEnvironment } from 'vite';

export function isolatedRuntimePlugin(): Plugin {
  // Invariant: WeakMap keyed by DevEnvironment preserves memory isolation and avoids leaks
  const envCaches = new WeakMap<DevEnvironment, Map<string, string>>();

  return {
    name: 'isolated-runtime-plugin',
    resolveId(id) {
      // Vite 6: explicitly check current compilation environment
      const currentEnv = this.environment as DevEnvironment;
      if (!envCaches.has(currentEnv)) {
        envCaches.set(currentEnv, new Map());
      }
      const cache = envCaches.get(currentEnv)!;
      if (cache.has(id)) {
        return cache.get(id);
      }

      if (id === 'virtual:runtime-config') {
        // Resolve differently based on Vite 6 environment name
        const resolved = currentEnv.name === 'client' 
          ? '/src/config.client.ts' 
          : '/src/config.server.ts';
        cache.set(id, resolved);
        return resolved;
      }
    },
    transform(code, id) {
      // Invariant: Never emit sensitive server data to client environment
      if (id.includes('runtime-config') && this.environment.name === 'client') {
        return `export const clientConfig = { publicUrl: '/api' };`;
      }
    }
  };
}
```

### Custom Dev Server Execution: Legacy ssrLoadModule vs Vite 6 Environment Runner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: `server.ssrLoadModule` forces execution through a legacy single-runtime Node.js context, breaking Edge/Workerd invariants and leaking Node builtins into non-Node targets.
```typescript
import { ViteDevServer } from 'vite';

export async function handleRequest(server: ViteDevServer, url: string, runtime: 'node' | 'edge') {
  // ANTI-PATTERN: Monolithic ssrLoadModule executes all runtimes inside the host Node.js process
  // This leaks Node.js globals and built-in modules into Edge runtime simulations
  const mod = await server.ssrLoadModule('/src/entry.server.ts');
  return mod.render(url);
}
```

#### Production Standard (Correct)
> **Standard**: Directly targets the configured Vite 6 `Environment` runner (`server.environments[runtime].runner.executeId()`), ensuring accurate runtime environment emulation (e.g., Cloudflare workerd vs Node.js) with independent module graph invalidation.
```typescript
import { ViteDevServer } from 'vite';

export async function handleRequest(server: ViteDevServer, url: string, runtime: 'ssr' | 'edge') {
  // Vite 6 Invariant: Access specific environment runner to guarantee strict runtime isolation
  const targetEnv = server.environments[runtime];
  if (!targetEnv) {
    throw new Error(`Environment '${runtime}' is not configured in Vite 6 server`);
  }

  // Uses the environment-specific ModuleRunner (e.g. Workerd / Node isolated runner)
  const mod = await targetEnv.runner.executeId('/src/entry.server.ts');
  return mod.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 Multi-Runtime Module Isolation Invariant

Vite 6 Environment API Multi-Runtime Module Isolation Invariant defines an industrial-grade behavioral standard for frontend engineering. Enforces complete memory, module graph, and execution isolation across compilation targets (client, edge/workerd, node) via the Vite 6 Environment API. Prevents cross-runtime prototype pollution, server secret leakage into client bundles, and broken transform caches caused by shared plugin state. Deprecates legacy monolithic SSR primitives in favor of per-environment module runners and isolated graph invalidation. 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: Leaking Shared Plugin State and Cross-Executing Code Across Vite 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 DriftLeaking Shared Plugin State and Cross-Executing Code Across Vite 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 scope plugin transform hooks, caches, and metadata to specific runtime environments using `this.environment.name` or `this.environment.mode`.

Engineers MUST ALWAYS scope plugin transform hooks, caches, and metadata to specific runtime environments using `this.environment.name` or `this.environment.mode`.

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 singleton state in Vite plugin closures across multiple environments.

Engineers MUST NOT maintain shared mutable singleton state in Vite plugin closures across multiple environments.

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 use `server.environments[name].runner.executeId()` instead of the legacy `server.ssrLoadModule()` when evaluating modules dynamically across heterogeneous runtimes.

Engineers MUST use `server.environments[name].runner.executeId()` instead of the legacy `server.ssrLoadModule()` when evaluating modules dynamically across heterogeneous runtimes.

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 target Hot Module Replacement (HMR) and module invalidation exclusively to the corresponding runtime module graph via `this.environment.moduleGraph` or `server.environments[name].moduleGraph`.

Engineers MUST target Hot Module Replacement (HMR) and module invalidation exclusively to the corresponding runtime module graph via `this.environment.moduleGraph` or `server.environments[name].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

Plugins targeting multiple environments MUST use the Vite 6 `perEnvironmentPlugin` API or branch logic explicitly per `Environment` instance to prevent Node-specific polyfills from leaking into Edge or Client graphs.

Plugins targeting multiple environments MUST use the Vite 6 `perEnvironmentPlugin` API or branch logic explicitly per `Environment` instance to prevent Node-specific polyfills from leaking into Edge or Client 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.
6

Components and application code NEVER import from environment-restricted entrypoints without conditional package exports or environment-specific module resolution guards.

Components and application code NEVER import from environment-restricted entrypoints without conditional package exports or environment-specific module resolution guards.

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

Enforces complete memory, module graph, and execution isolation across compilation targets (client, edge/workerd, node) via the Vite 6 Environment API. Prevents cross-runtime prototype pollution, server secret leakage into client bundles, and broken transform caches caused by shared plugin state. Deprecates legacy monolithic SSR primitives in favor of per-environment module runners and isolated graph invalidation. 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 (Leaking Shared Plugin State and Cross-Executing Code Across Vite 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