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-runtimes-production-standard

Vite 6 Environment API & Multi-Runtimes Architecture Standard

Vite 6 deprecates monolithic SSR transforms in favor of the Environment API, isolating module graphs and module runners across distinct runtimes (Node.js, Edge, workerd, and Client). Conflating environment module graphs or invoking deprecated APIs like `ssrLoadModule` causes cross-runtime state leakage, broken HMR transport boundaries, and unhandled execution crashes. Strict boundary isolation across `server.environments` MUST be enforced to guarantee deterministic compilation and Hot Module Replacement.

Prohibited Anti-Pattern: Defaulting to legacy `ssrLoadModule` and accessing shared server transform caches across multi-runtime targets instead of scoped `DevEnvironment` instances.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API & Multi-Runtimes Architecture Standard - Vite 6 deprecates monolithic SSR transforms in favor of the Environment API, isolating module graphs and module runners across distinct runtimes (Node.js, Edge, workerd, and Client). Conflating environment module graphs or invoking deprecated APIs like `ssrLoadModule` causes cross-runtime state leakage, broken HMR transport boundaries, and unhandled execution crashes. Strict boundary isolation across `server.environments` MUST be enforced to guarantee deterministic compilation and Hot Module Replacement.
globs: vite.config.*, **/server/**/*.{ts,js,mjs}, **/src/**/*.{ts,js,tsx,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-environment-api-multi-runtimes-production-standard"
---

# Vite 6 Environment API & Multi-Runtimes Architecture Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Defaulting to legacy `ssrLoadModule` and accessing shared server transform caches across multi-runtime targets instead of scoped `DevEnvironment` instances.

## System Constraints
You are an expert Vite 6 systems architect specializing in runtime isolation and the Vite Environment API. You MUST ensure that multi-runtime execution boundaries (Client, SSR, Edge/workerd) are maintained through independent `DevEnvironment` definitions and `ModuleRunner` abstractions. You MUST reject all legacy Vite 5 SSR APIs (`ssrLoadModule`, `ssrTransform`, `ssrFixStacktrace`) and enforce rigorous HMR channel scoping.

## Strict Guidelines
- Developers MUST NOT use legacy Vite SSR APIs (`server.ssrLoadModule`, `server.ssrTransform`, `server.ssrFixStacktrace`) and MUST migrate to `server.environments[name]` and the decoupled `ModuleRunner` API.
- Custom runtimes (such as Cloudflare workerd or V8 Isolates) MUST implement a dedicated `DevEnvironment` with configured `transport` and `runner` instances to prevent Node.js built-ins from leaking into isolated environments.
- Custom plugins injecting runtime hooks MUST check `this.environment.name` instead of relying on legacy `options.ssr` boolean flags.
- HMR event listeners and hot updates MUST ALWAYS be scoped to their targeted environment via `environment.hot.send` to prevent broadcast contamination across unrelated runtimes.
- Plugins that modify module graphs MUST interact solely with `this.environment.moduleGraph` to preserve discrete resolution caches per target runtime.

## Bad vs Good Implementations
### Migrating from Legacy ssrLoadModule to Vite 6 Environment API and ModuleRunner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Vite 6 obsoletes `server.ssrLoadModule` and `server.ssrFixStacktrace`. Using them bypasses the Vite 6 Environment API, forcing all server executions through the legacy Node.js SSR pipeline, breaking custom runtime semantics (e.g., workerd/edge), and causing memory leaks across distinct module graphs.
```typescript
import type { ViteDevServer } from 'vite';

export async function handleDevRequest(
  server: ViteDevServer,
  url: string,
  runtimeTarget: 'ssr' | 'edge'
): Promise<unknown> {
  // Anti-pattern: Using legacy ssrLoadModule across runtimes.
  // This ignores Vite 6 independent environment isolation and leaks Node context.
  try {
    const entryModule = await server.ssrLoadModule(url);
    return entryModule;
  } catch (error) {
    server.ssrFixStacktrace(error as Error);
    throw error;
  }
}
```

#### Production Standard (Correct)
> **Standard**: This approach targets the discrete `DevEnvironment` registered in `server.environments[name]`, creates an isolated `ModuleRunner`, passes execution through the explicit transport channel, and avoids cross-runtime module graph pollution.
```typescript
import { createServer, type ViteDevServer } from 'vite';
import { ModuleRunner, ESModulesRunner } from 'vite/module-runner';

export async function loadEnvironmentEntry(
  server: ViteDevServer,
  environmentName: string,
  entryUrl: string
): Promise<Record<string, unknown>> {
  const environment = server.environments[environmentName];
  if (!environment) {
    throw new Error(`[vite] Environment "${environmentName}" is not registered on the dev server.`);
  }

  // Use isolated ModuleRunner bound to the target environment's transport
  const runner = new ModuleRunner(
    {
      root: server.config.root,
      transport: {
        invoke: async (payload) => {
          return await environment.hot.handleInvoke(payload);
        }
      }
    },
    new ESModulesRunner()
  );

  try {
    const mod = await runner.import(entryUrl);
    return mod as Record<string, unknown>;
  } catch (error) {
    if (error instanceof Error) {
      // Fix stack traces directly through the targeted environment
      environment.hot.send({
        type: 'error',
        err: {
          message: error.message,
          stack: error.stack ?? ''
        }
      });
    }
    throw error;
  } finally {
    await runner.close();
  }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Vite 6 Environment API & Multi-Runtimes Architecture Standard

Vite 6 Environment API & Multi-Runtimes Architecture Standard defines an industrial-grade behavioral standard for frontend engineering. Vite 6 deprecates monolithic SSR transforms in favor of the Environment API, isolating module graphs and module runners across distinct runtimes (Node.js, Edge, workerd, and Client). Conflating environment module graphs or invoking deprecated APIs like `ssrLoadModule` causes cross-runtime state leakage, broken HMR transport boundaries, and unhandled execution crashes. Strict boundary isolation across `server.environments` MUST be enforced to guarantee deterministic compilation and Hot Module Replacement. 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: Defaulting to legacy `ssrLoadModule` and accessing shared server transform caches across multi-runtime targets instead of scoped `DevEnvironment` instances. 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 DriftDefaulting to legacy `ssrLoadModule` and accessing shared server transform caches across multi-runtime targets instead of scoped `DevEnvironment` instances.Critical
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

Developers MUST NOT use legacy Vite SSR APIs (`server.ssrLoadModule`, `server.ssrTransform`, `server.ssrFixStacktrace`) and MUST migrate to `server.environments[name]` and the decoupled `ModuleRunner` API.

Developers MUST NOT use legacy Vite SSR APIs (`server.ssrLoadModule`, `server.ssrTransform`, `server.ssrFixStacktrace`) and MUST migrate to `server.environments[name]` and the decoupled `ModuleRunner` API.

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

Custom runtimes (such as Cloudflare workerd or V8 Isolates) MUST implement a dedicated `DevEnvironment` with configured `transport` and `runner` instances to prevent Node.js built-ins from leaking into isolated environments.

Custom runtimes (such as Cloudflare workerd or V8 Isolates) MUST implement a dedicated `DevEnvironment` with configured `transport` and `runner` instances to prevent Node.js built-ins from leaking into isolated 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

Custom plugins injecting runtime hooks MUST check `this.environment.name` instead of relying on legacy `options.ssr` boolean flags.

Custom plugins injecting runtime hooks MUST check `this.environment.name` instead of relying on legacy `options.ssr` boolean flags.

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

HMR event listeners and hot updates MUST ALWAYS be scoped to their targeted environment via `environment.hot.send` to prevent broadcast contamination across unrelated runtimes.

HMR event listeners and hot updates MUST ALWAYS be scoped to their targeted environment via `environment.hot.send` to prevent broadcast contamination across unrelated 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.
5

Plugins that modify module graphs MUST interact solely with `this.environment.moduleGraph` to preserve discrete resolution caches per target runtime.

Plugins that modify module graphs MUST interact solely with `this.environment.moduleGraph` to preserve discrete resolution caches per target runtime.

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-Runtimes Architecture Standard critical for AI coding assistants?

Vite 6 deprecates monolithic SSR transforms in favor of the Environment API, isolating module graphs and module runners across distinct runtimes (Node.js, Edge, workerd, and Client). Conflating environment module graphs or invoking deprecated APIs like `ssrLoadModule` causes cross-runtime state leakage, broken HMR transport boundaries, and unhandled execution crashes. Strict boundary isolation across `server.environments` MUST be enforced to guarantee deterministic compilation and Hot Module Replacement. 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 (Defaulting to legacy `ssrLoadModule` and accessing shared server transform caches across multi-runtime targets instead of scoped `DevEnvironment` instances.) 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