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-503

Vite 6 Multi-Environment Isolation and Cross-Runtime Boundary Enforcement

Vite 6 Environment API allows distinct execution contexts (Node SSR, Workerd edge, React Server Components, and client bundles) to run in unified dev and build pipelines. In multi-runtime setups, you must enforce strict module boundary isolation, dedicated DevEnvironment configs, and explicit runtime export conditions to prevent host Node.js globals and stateful module graphs from cross-pollinating isolated runtimes.

Prohibited Anti-Pattern: Cross-Pollinating Node.js Globals and Sharing Module Execution Caches Across Isolated Vite 6 Environments

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Multi-Environment Isolation and Cross-Runtime Boundary Enforcement - Vite 6 Environment API allows distinct execution contexts (Node SSR, Workerd edge, React Server Components, and client bundles) to run in unified dev and build pipelines. In multi-runtime setups, you must enforce strict module boundary isolation, dedicated DevEnvironment configs, and explicit runtime export conditions to prevent host Node.js globals and stateful module graphs from cross-pollinating isolated runtimes.
globs: vite.config.{ts,js,mjs}, 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-multi-runtime-isolation-vite-6-environme-503"
---

# Vite 6 Multi-Environment Isolation and Cross-Runtime Boundary Enforcement

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Pollinating Node.js Globals and Sharing Module Execution Caches Across Isolated Vite 6 Environments

## System Constraints
You are a Principal Software Architect enforcing strict module boundary isolation and runtime guarantees using the Vite 6 Environment API. You must mandate discrete environment definitions for heterogeneous execution contexts (e.g., client, ssr running in Node, edge running in Workerd/Miniflare). Ensure that host Node built-ins, shared memory singletons, and unisolated module graphs never leak between client, Node, and edge worker environments.

## Strict Guidelines
- Engineers MUST ALWAYS configure runtime-specific conditions inside discrete `environments.<name>.resolve.conditions` rather than relying on top-level `resolve.conditions`.
- Engineers MUST NOT invoke deprecated `server.ssrLoadModule` or `server.ssrFixStacktrace`; migrate exclusively to `server.environments[name].runner.import()` or `fetchModule()` depending on whether the target environment is a `RunnableDevEnvironment` or `FetchableDevEnvironment`.
- Code executing inside edge/Workerd environments MUST NOT import Node.js core APIs (`node:fs`, `node:child_process`, `node:os`) unless specifically provided by the runtime's compatibility flags.
- Services running in heterogeneous environments MUST NOT access `process.env` directly; access configuration via explicit runtime injection (e.g., `import.meta.env` or Cloudflare `env` binding context passed through the environment dispatcher).
- Module singletons (e.g., in-memory caches, database clients) MUST NEVER be imported across environment boundaries; communicate strictly via serializable RPCs, HTTP, or custom WebSocket dispatch channels.
- Build pipelines MUST explicitly invoke `builder.build(builder.environments[name])` per environment target instead of running monolithic client/server builds that conflate asset resolution graphs.

## Bad vs Good Implementations
### Vite 6 Multi-Environment Configuration with Node and Workerd Runtime Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Global definitions of 'conditions' and 'ssr.target' break module isolation across different targets. Workerd-targeted modules resolve Node conditions, while Node server modules attempt to execute with webworker constraints. Module caches and globals cross-contaminate between client, worker, and Node processes.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Vite 5 legacy pattern conflating edge and node runtimes
// into a single generic SSR target, causing cross-runtime leaks
export default defineConfig({
  ssr: {
    target: 'webworker', // Overrides SSR globally; breaks Node.js SSR services
    noExternal: true,
  },
  resolve: {
    // Host-polluting conditions applied globally across client and worker
    conditions: ['workerd', 'worker', 'node'],
  },
  server: {
    // Deprecated Vite 5 hook allowing Node globals to leak into worker runner
    middlewareMode: true,
  }
});
```

#### Production Standard (Correct)
> **Standard**: Declaring distinct environments ('client', 'ssrNode', 'edgeWorker') establishes segregated module graphs, dedicated module runners, and strict runtime condition resolution. Edge builds will fail fast if attempting to import Node-specific modules, while Node builds preserve full platform compatibility.
```typescript
import { defineConfig } from 'vite';

// PRODUCTION PATTERN: Vite 6 Environment API with strict per-runtime isolation
export default defineConfig({
  environments: {
    client: {
      consumer: 'client',
      build: {
        outDir: 'dist/client',
      },
    },
    ssrNode: {
      consumer: 'server',
      resolve: {
        conditions: ['node'],
        externalConditions: ['node'],
      },
      build: {
        outDir: 'dist/server/node',
      },
    },
    edgeWorker: {
      consumer: 'server',
      resolve: {
        conditions: ['workerd', 'worker', 'browser'],
        externalConditions: ['workerd', 'worker'],
      },
      build: {
        outDir: 'dist/server/edge',
      },
    },
  },
  builder: {
    async buildApp(builder) {
      // Execute builds sequentially or in parallel without graph interference
      await builder.build(builder.environments.client);
      await builder.build(builder.environments.ssrNode);
      await builder.build(builder.environments.edgeWorker);
    },
  },
});
```

### Executing Isolated Server-Side Code via Vite 6 DevEnvironment Runner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using 'server.ssrLoadModule' bypasses environment boundaries and loads edge code directly into the Vite host Node.js process. Native Node APIs will silently pass in development and immediately crash in the target runtime (e.g. Cloudflare Workers).
```typescript
import type { ViteDevServer } from 'vite';

// ANTI-PATTERN: Using deprecated ssrLoadModule executes code on host Node runner
// even if the module is intended for a Workerd isolate
export async function handleRequest(server: ViteDevServer, url: string) {
  const mod = await server.ssrLoadModule('/src/edge-entry.ts');
  // process.env and Node globals are implicitly accessible here, masking edge runtime failures
  return mod.default.fetch(new Request(url));
}
```

#### Production Standard (Correct)
> **Standard**: Targeting the specific `RunnableDevEnvironment` guarantees execution within that environment's isolated module graph and runner context. Any attempted access to foreign runtime globals will fail deterministically during local development.
```typescript
import type { ViteDevServer } from 'vite';
import type { RunnableDevEnvironment } from 'vite';

// PRODUCTION PATTERN: Dispatching execution strictly to the designated DevEnvironment
export async function handleRequest(server: ViteDevServer, url: string, runtime: 'ssrNode' | 'edgeWorker') {
  const targetEnv = server.environments[runtime];
  if (!targetEnv) {
    throw new Error(`Environment [${runtime}] is not configured in Vite server.`);
  }

  // Enforce runner interface for runnable environments (e.g., Node / Worker isolate runner)
  const runnable = targetEnv as RunnableDevEnvironment;
  const mod = await runnable.runner.import('/src/entry.ts');

  return mod.default.fetch(new Request(url));
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Vite 6 Multi-Environment Isolation and Cross-Runtime Boundary Enforcement

Vite 6 Multi-Environment Isolation and Cross-Runtime Boundary Enforcement defines an industrial-grade behavioral standard for frontend engineering. Vite 6 Environment API allows distinct execution contexts (Node SSR, Workerd edge, React Server Components, and client bundles) to run in unified dev and build pipelines. In multi-runtime setups, you must enforce strict module boundary isolation, dedicated DevEnvironment configs, and explicit runtime export conditions to prevent host Node.js globals and stateful module graphs from cross-pollinating isolated runtimes. 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-Pollinating Node.js Globals and Sharing Module Execution Caches Across Isolated Vite 6 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 DriftCross-Pollinating Node.js Globals and Sharing Module Execution Caches Across Isolated Vite 6 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 configure runtime-specific conditions inside discrete `environments.<name>.resolve.conditions` rather than relying on top-level `resolve.conditions`.

Engineers MUST ALWAYS configure runtime-specific conditions inside discrete `environments.<name>.resolve.conditions` rather than relying on top-level `resolve.conditions`.

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 invoke deprecated `server.ssrLoadModule` or `server.ssrFixStacktrace`

Engineers MUST NOT invoke deprecated `server.ssrLoadModule` or `server.ssrFixStacktrace`; migrate exclusively to `server.environments[name].runner.import()` or `fetchModule()` depending on whether the target environment is a `RunnableDevEnvironment` or `FetchableDevEnvironment`.

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

Code executing inside edge/Workerd environments MUST NOT import Node.js core APIs (`node

Code executing inside edge/Workerd environments MUST NOT import Node.js core APIs (`node:fs`, `node:child_process`, `node:os`) unless specifically provided by the runtime's compatibility 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

Services running in heterogeneous environments MUST NOT access `process.env` directly

Services running in heterogeneous environments MUST NOT access `process.env` directly; access configuration via explicit runtime injection (e.g., `import.meta.env` or Cloudflare `env` binding context passed through the environment dispatcher).

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

Module singletons (e.g., in-memory caches, database clients) MUST NEVER be imported across environment boundaries

Module singletons (e.g., in-memory caches, database clients) MUST NEVER be imported across environment boundaries; communicate strictly via serializable RPCs, HTTP, or custom WebSocket dispatch 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.
6

Build pipelines MUST explicitly invoke `builder.build(builder.environments[name])` per environment target instead of running monolithic client/server builds that conflate asset resolution graphs.

Build pipelines MUST explicitly invoke `builder.build(builder.environments[name])` per environment target instead of running monolithic client/server builds that conflate asset resolution 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 Vite 6 Multi-Environment Isolation and Cross-Runtime Boundary Enforcement critical for AI coding assistants?

Vite 6 Environment API allows distinct execution contexts (Node SSR, Workerd edge, React Server Components, and client bundles) to run in unified dev and build pipelines. In multi-runtime setups, you must enforce strict module boundary isolation, dedicated DevEnvironment configs, and explicit runtime export conditions to prevent host Node.js globals and stateful module graphs from cross-pollinating isolated runtimes. 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-Pollinating Node.js Globals and Sharing Module Execution Caches Across Isolated Vite 6 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