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

Vite 6 Environment API Multi-Runtime Module Sandboxing and Isolation

Enforces architectural isolation of distinct module graphs and execution contexts across Node.js, Edge (workerd), and browser targets using the Vite 6 Environment API. Prevents cross-runtime global state leakage, invalid Node.js built-in resolution in Edge/client bundles, and cross-polluted module caches in universal SSR pipelines.

Prohibited Anti-Pattern: Cross-Runtime Module Graph Pollution and Shared Global State in Universal Vite 6 SSR

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime Module Sandboxing and Isolation - Enforces architectural isolation of distinct module graphs and execution contexts across Node.js, Edge (workerd), and browser targets using the Vite 6 Environment API. Prevents cross-runtime global state leakage, invalid Node.js built-in resolution in Edge/client bundles, and cross-polluted module caches in universal SSR pipelines.
globs: vite.config.ts, vite.config.*.ts, src/**/*.{ts,tsx}, server/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-multi-runtime-sandboxing"
---

# Vite 6 Environment API Multi-Runtime Module Sandboxing and Isolation

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Runtime Module Graph Pollution and Shared Global State in Universal Vite 6 SSR

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API standards for multi-runtime architectures. Universal SSR applications frequently suffer from silent module poisoning when server-side Node.js, Edge runtimes (e.g., Cloudflare Workers/workerd), and client browser runtimes share module nodes, resolution conditions, or execution runners. You must mandate strict physical separation of Vite 6 dev environments, runtime-specific resolution conditions, isolated ModuleRunner instances, and clean global scope encapsulation.

## Strict Guidelines
- Engineers MUST configure distinct runtime boundaries under the Vite 6 `environments` configuration key (e.g., `client`, `ssr`, and `edge`) rather than relying on legacy monolithic `ssr` options.
- Engineers MUST specify explicit `resolve.conditions` and `resolve.externalConditions` for each configured environment to prevent Node.js built-ins (`fs`, `path`, `node:crypto`) from leaking into Edge or Client module graphs.
- Engineers MUST NOT use deprecated `viteDevServer.ssrLoadModule()` when orchestrating multi-runtime SSR; they MUST use `server.environments[name].runner` or instantiate runtime-dedicated `ModuleRunner` instances.
- Services running universal SSR MUST NOT bind execution context to un-namespaced `globalThis` singletons across environment boundaries; execution contexts MUST be scoped to per-request or runtime-isolated storage.
- Plugins MUST target specific environments using the `applyToEnvironment` hook or check `this.environment.name` inside plugin hooks to prevent client transforms from executing on edge/server modules and vice-versa.

## Bad vs Good Implementations
### Multi-Runtime Vite Configuration with Environment API Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring SSR monolithically through the legacy top-level `ssr` block fails to segregate the module graph between different backend runtimes (e.g., Node.js vs Cloudflare workerd/Edge). Resolution conditions collide, causing Node built-ins to leak into non-Node targets, and prevents Vite 6 from optimizing per-runtime module transforms.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Monolithic SSR configuration attempting to serve both
// Node.js and Edge/Worker runtimes without isolated environment module graphs.
export default defineConfig({
  ssr: {
    // Leaks Node resolution conditions into Edge contexts
    target: 'node',
    noExternal: true,
  },
  build: {
    rollupOptions: {
      // Fragile dual-entrypoint branching without environment separation
      input: {
        client: './src/entry-client.tsx',
        server: './src/entry-server.tsx',
      },
    },
  },
});
```

#### Production Standard (Correct)
> **Standard**: Declaring distinct environment graphs under the `environments` root ensures that 'ssr' (Node.js) and 'edge' (workerd/V8 isolate) resolve modules under mutually exclusive runtime condition flags, preventing illegal built-in imports and enabling tailored compilation targets.
```typescript
import { defineConfig } from 'vite';

// PRODUCTION FIX: Explicitly configured Vite 6 Environment API with isolated module graphs
export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client',
        rollupOptions: {
          input: './src/entry-client.tsx',
        },
      },
    },
    ssr: {
      resolve: {
        conditions: ['node'],
        externalConditions: ['node'],
      },
      build: {
        outDir: 'dist/server',
        target: 'node22',
        rollupOptions: {
          input: './src/entry-node.tsx',
        },
      },
    },
    edge: {
      resolve: {
        conditions: ['workerd', 'worker', 'browser'],
        externalConditions: ['workerd', 'worker'],
      },
      build: {
        outDir: 'dist/edge',
        target: 'esnext',
        rollupOptions: {
          input: './src/entry-edge.tsx',
        },
      },
    },
  },
});
```

### Vite 6 Module Execution via Isolated ModuleRunner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mutating `globalThis` to emulate Edge runtime primitives while calling `ssrLoadModule` permanently corrupts the host Node.js environment. Subsequent calls to Node-targeted rendering will inherit unwanted mocks, and the module graph remains coupled to a single runtime instance.
```typescript
import type { ViteDevServer } from 'vite';

// ANTI-PATTERN: Using legacy ssrLoadModule across runtimes with mutable global state injection
export async function handleRequest(server: ViteDevServer, url: string, runtimeType: 'node' | 'edge') {
  // Contaminates the default Node.js SSR runtime with edge-specific global mocks
  if (runtimeType === 'edge') {
    (globalThis as Record<string, unknown>).WebSocket = class MockWebSocket {};
  }

  // ssrLoadModule executes inside the host Node.js process without graph isolation
  const entry = await server.ssrLoadModule('/src/entry-universal.tsx');
  return entry.render(url);
}
```

#### Production Standard (Correct)
> **Standard**: Utilizing `server.environments[runtimeType].runner` guarantees that imported modules are processed through that specific environment's transform pipeline, resolve conditions, and isolated cache, avoiding cross-contamination of globals or conflicting exports.
```typescript
import type { ViteDevServer } from 'vite';

interface UniversalHandler {
  render: (url: string) => Promise<string>;
}

// PRODUCTION FIX: Execute isolated ModuleRunners tied to explicit Vite 6 environments
export async function handleRequest(
  server: ViteDevServer,
  url: string,
  runtimeType: 'ssr' | 'edge'
): Promise<string> {
  const targetEnv = server.environments[runtimeType];
  if (!targetEnv) {
    throw new Error(`Unrecognized Vite 6 runtime environment: ${runtimeType}`);
  }

  // Access the isolated ModuleRunner configured specifically for this runtime's module graph
  const runner = targetEnv.runner;
  const entryModule = (await runner.import('/src/entry-' + runtimeType + '.tsx')) as UniversalHandler;

  return await entryModule.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 Sandboxing and Isolation

Vite 6 Environment API Multi-Runtime Module Sandboxing and Isolation defines an industrial-grade behavioral standard for frontend engineering. Enforces architectural isolation of distinct module graphs and execution contexts across Node.js, Edge (workerd), and browser targets using the Vite 6 Environment API. Prevents cross-runtime global state leakage, invalid Node.js built-in resolution in Edge/client bundles, and cross-polluted module caches in universal SSR pipelines. 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-Runtime Module Graph Pollution and Shared Global State in Universal Vite 6 SSR 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-Runtime Module Graph Pollution and Shared Global State in Universal Vite 6 SSRCritical
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 configure distinct runtime boundaries under the Vite 6 `environments` configuration key (e.g., `client`, `ssr`, and `edge`) rather than relying on legacy monolithic `ssr` options.

Engineers MUST configure distinct runtime boundaries under the Vite 6 `environments` configuration key (e.g., `client`, `ssr`, and `edge`) rather than relying on legacy monolithic `ssr` 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 specify explicit `resolve.conditions` and `resolve.externalConditions` for each configured environment to prevent Node.js built-ins (`fs`, `path`, `node

Engineers MUST specify explicit `resolve.conditions` and `resolve.externalConditions` for each configured environment to prevent Node.js built-ins (`fs`, `path`, `node:crypto`) from leaking into Edge or Client module 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.
3

Engineers MUST NOT use deprecated `viteDevServer.ssrLoadModule()` when orchestrating multi-runtime SSR

Engineers MUST NOT use deprecated `viteDevServer.ssrLoadModule()` when orchestrating multi-runtime SSR; they MUST use `server.environments[name].runner` or instantiate runtime-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.
4

Services running universal SSR MUST NOT bind execution context to un-namespaced `globalThis` singletons across environment boundaries

Services running universal SSR MUST NOT bind execution context to un-namespaced `globalThis` singletons across environment boundaries; execution contexts MUST be scoped to per-request or runtime-isolated storage.

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 MUST target specific environments using the `applyToEnvironment` hook or check `this.environment.name` inside plugin hooks to prevent client transforms from executing on edge/server modules and vice-versa.

Plugins MUST target specific environments using the `applyToEnvironment` hook or check `this.environment.name` inside plugin hooks to prevent client transforms from executing on edge/server modules and vice-versa.

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

Enforces architectural isolation of distinct module graphs and execution contexts across Node.js, Edge (workerd), and browser targets using the Vite 6 Environment API. Prevents cross-runtime global state leakage, invalid Node.js built-in resolution in Edge/client bundles, and cross-polluted module caches in universal SSR pipelines. 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-Runtime Module Graph Pollution and Shared Global State in Universal Vite 6 SSR) 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