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

Vite 6 Environment API Multi-Runtime Isolation and Boundary Protocol

Enforces strict isolation across client, Node.js (SSR), and Edge/workerd runtime module graphs using the Vite 6 Environment API. Prevents runtime cross-contamination, illegal module execution via deprecated APIs, and leakage of Node.js-specific built-ins into edge and browser compilation targets.

Prohibited Anti-Pattern: Cross-Contaminating Multi-Target Module Graphs and Relying on Deprecated Single-SSR APIs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime Isolation and Boundary Protocol - Enforces strict isolation across client, Node.js (SSR), and Edge/workerd runtime module graphs using the Vite 6 Environment API. Prevents runtime cross-contamination, illegal module execution via deprecated APIs, and leakage of Node.js-specific built-ins into edge and browser compilation targets.
globs: vite.config.ts, vite.config.*.ts, src/**/*.{ts,tsx}, app/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-multi-runtime-isolation-vite-6-environme-532"
---

# Vite 6 Environment API Multi-Runtime Isolation and Boundary Protocol

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Contaminating Multi-Target Module Graphs and Relying on Deprecated Single-SSR APIs

## System Constraints
You are a Principal Software Architect enforcing the Vite 6 Environment API Multi-Runtime Protocol. You must enforce strict runtime isolation between client, Node.js SSR, and Edge compilation targets. Prohibit legacy Vite SSR idioms such as `server.ssrLoadModule`, `server.ssrFixStacktrace`, and untyped global runtime state. Mandate granular environment definitions, environment-aware plugin lifecycle hooks using `this.environment`, and dedicated ModuleRunner instances for non-Node and Node runtimes alike.

## Strict Guidelines
- Engineers MUST ALWAYS declare distinct compilation environments in Vite 6 configs under `environments.<name>` with dedicated resolve conditions, externalization policies, and build options.
- Engineers MUST NOT call deprecated Vite 5 SSR methods (`server.ssrLoadModule`, `server.ssrTransform`, `server.ssrFixStacktrace`); all runtime execution MUST use `server.environments[name].runner.import()` or dedicated `ModuleRunner` instances.
- Plugins MUST check `this.environment.name` in hook implementations rather than inspecting deprecated options such as `options?.ssr` or `config.build.ssr`.
- Edge-targeted environments MUST configure `resolve.conditions` containing runtime identifiers (e.g., `['edge-light', 'worker', 'browser']`) and MUST explicitly forbid Node.js core modules (`node:*`).
- Shared utilities MUST NOT reference runtime-specific globals (`process`, `window`, `caches`, `Deno`) directly without abstraction layers or compile-time guard validations.
- Custom environments using out-of-process or isolated execution (e.g., Cloudflare workerd, Deno) MUST subclass or implement `DevEnvironment` or `RunnableDevEnvironment` using explicit transport communication channels.

## Bad vs Good Implementations
### Configuring Multi-Runtime Isolation (Vite 6 Environment API vs Legacy SSR)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on legacy Vite SSR flags (`build.ssr`, `ssr` root options) and binary `options.ssr` checks in plugins. If the SSR environment executes in an edge worker runtime, injecting 'node:fs' will cause catastrophic runtime failures.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Deprecated Vite 5 single-SSR mindset with monolithic config
export default defineConfig({
  build: {
    ssr: true,
  },
  ssr: {
    noExternal: true,
  },
  plugins: [{
    name: 'custom-runtime-injector',
    transform(code, id, options) {
      // Flawed: treats SSR as binary (client vs node)
      const isSSR = Boolean(options?.ssr);
      if (isSSR) {
        return `import 'node:fs';
${code}`;
      }
      return code;
    }
  }]
});
```

#### Production Standard (Correct)
> **Standard**: Defines explicit environments (`client`, `ssr`, `edge`) with targeted resolve conditions and output directories. The plugin consumes `this.environment.name` to enforce architectural invariants at the module boundary.
```typescript
import { defineConfig } from 'vite';

export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client'
      }
    },
    ssr: {
      build: {
        outDir: 'dist/ssr',
        target: 'node20'
      },
      resolve: {
        conditions: ['node', 'import']
      }
    },
    edge: {
      build: {
        outDir: 'dist/edge',
        target: 'esnext'
      },
      resolve: {
        conditions: ['edge-light', 'worker', 'browser'],
        externalConditions: ['edge-light', 'worker']
      }
    }
  },
  plugins: [{
    name: 'runtime-aware-injector',
    transform(code, id) {
      // Enforce isolation via Vite 6 Environment context
      if (this.environment.name === 'edge') {
        if (code.includes('node:')) {
          this.error(`Node built-ins are prohibited in edge target: ${id}`);
        }
      }
      return null;
    }
  }]
});
```

### Executing Code in Dev Server via ModuleRunner vs ssrLoadModule

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses deprecated `server.ssrLoadModule` and `server.ssrFixStacktrace`, which bypasses multi-environment instances and fails when the runtime target is non-Node (e.g., Cloudflare Workers / workerd).
```typescript
import type { ViteDevServer } from 'vite';

// ANTI-PATTERN: Deprecated Vite 5 ssrLoadModule ignores Environment API
export async function handleRequest(server: ViteDevServer, url: string) {
  const mod = await server.ssrLoadModule('/src/entry.server.ts');
  server.ssrFixStacktrace(new Error('test'));
  return mod.render(url);
}
```

#### Production Standard (Correct)
> **Standard**: Accesses the specific runtime environment via `server.environments[name]` and executes code safely via `environment.runner.import()`, adhering to the Vite 6 multi-runtime protocol.
```typescript
import type { ViteDevServer } from 'vite';

export async function handleRequest(
  server: ViteDevServer,
  targetRuntime: 'ssr' | 'edge',
  url: string
) {
  const environment = server.environments[targetRuntime];
  if (!environment || !('runner' in environment)) {
    throw new Error(`Target runtime "${targetRuntime}" is not runnable in this dev configuration.`);
  }

  // Vite 6 ModuleRunner API execution scoped to target DevEnvironment
  const mod = await environment.runner.import('/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 Isolation and Boundary Protocol

Vite 6 Environment API Multi-Runtime Isolation and Boundary Protocol defines an industrial-grade behavioral standard for frontend engineering. Enforces strict isolation across client, Node.js (SSR), and Edge/workerd runtime module graphs using the Vite 6 Environment API. Prevents runtime cross-contamination, illegal module execution via deprecated APIs, and leakage of Node.js-specific built-ins into edge and browser compilation targets. 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-Contaminating Multi-Target Module Graphs and Relying on Deprecated Single-SSR APIs 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-Contaminating Multi-Target Module Graphs and Relying on Deprecated Single-SSR APIsCritical
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 declare distinct compilation environments in Vite 6 configs under `environments.<name>` with dedicated resolve conditions, externalization policies, and build options.

Engineers MUST ALWAYS declare distinct compilation environments in Vite 6 configs under `environments.<name>` with dedicated resolve conditions, externalization policies, and build options.

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 call deprecated Vite 5 SSR methods (`server.ssrLoadModule`, `server.ssrTransform`, `server.ssrFixStacktrace`)

Engineers MUST NOT call deprecated Vite 5 SSR methods (`server.ssrLoadModule`, `server.ssrTransform`, `server.ssrFixStacktrace`); all runtime execution MUST use `server.environments[name].runner.import()` or dedicated `ModuleRunner` 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

Plugins MUST check `this.environment.name` in hook implementations rather than inspecting deprecated options such as `options?.ssr` or `config.build.ssr`.

Plugins MUST check `this.environment.name` in hook implementations rather than inspecting deprecated options such as `options?.ssr` or `config.build.ssr`.

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-targeted environments MUST configure `resolve.conditions` containing runtime identifiers (e.g., `['edge-light', 'worker', 'browser']`) and MUST explicitly forbid Node.js core modules (`node

Edge-targeted environments MUST configure `resolve.conditions` containing runtime identifiers (e.g., `['edge-light', 'worker', 'browser']`) and MUST explicitly forbid Node.js core modules (`node:*`).

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

Shared utilities MUST NOT reference runtime-specific globals (`process`, `window`, `caches`, `Deno`) directly without abstraction layers or compile-time guard validations.

Shared utilities MUST NOT reference runtime-specific globals (`process`, `window`, `caches`, `Deno`) directly without abstraction layers or compile-time guard validations.

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

Custom environments using out-of-process or isolated execution (e.g., Cloudflare workerd, Deno) MUST subclass or implement `DevEnvironment` or `RunnableDevEnvironment` using explicit transport communication channels.

Custom environments using out-of-process or isolated execution (e.g., Cloudflare workerd, Deno) MUST subclass or implement `DevEnvironment` or `RunnableDevEnvironment` using explicit transport communication channels.

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 Isolation and Boundary Protocol critical for AI coding assistants?

Enforces strict isolation across client, Node.js (SSR), and Edge/workerd runtime module graphs using the Vite 6 Environment API. Prevents runtime cross-contamination, illegal module execution via deprecated APIs, and leakage of Node.js-specific built-ins into edge and browser compilation targets. 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-Contaminating Multi-Target Module Graphs and Relying on Deprecated Single-SSR APIs) 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