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

Vite 6 Environment API Multi-Runtime Module Sandboxing Standard

Enforces strict runtime boundary isolation when cross-compiling shared libraries across browser, edge, Node.js, and workerd targets within a single Vite 6 dev server instance. Guarantees that module graphs, resolve conditions, and transform pipelines remain sandboxed to prevent runtime global contamination and invalid target execution.

Prohibited Anti-Pattern: Cross-contaminating module graphs and resolve conditions across browser, workerd, and Node.js runtimes using legacy single-target Vite paradigms.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime Module Sandboxing Standard - Enforces strict runtime boundary isolation when cross-compiling shared libraries across browser, edge, Node.js, and workerd targets within a single Vite 6 dev server instance. Guarantees that module graphs, resolve conditions, and transform pipelines remain sandboxed to prevent runtime global contamination and invalid target execution.
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/vite-6-environment-api-runtime-sandboxing"
---

# Vite 6 Environment API Multi-Runtime Module Sandboxing Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-contaminating module graphs and resolve conditions across browser, workerd, and Node.js runtimes using legacy single-target Vite paradigms.

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API multi-runtime module sandboxing. Vite 6 decouples the client and SSR build pipelines into isolated DevEnvironments (e.g., client, ssr, edge, workerd). You must ensure all configurations, plugins, and imports strictly maintain runtime boundary isolation, prevent cross-environment cache contamination, and reject legacy ssrLoadModule patterns.

## Strict Guidelines
- Engineers MUST ALWAYS configure runtime targets using the Vite 6 top-level `environments` configuration key instead of legacy overloaded `ssr` or conditional plugin arrays.
- Engineers MUST ALWAYS qualify plugin caches and transform states with `this.environment.name` inside Vite plugin hooks to prevent cross-runtime AST or bytecode leakage.
- Engineers MUST NOT use deprecated `server.ssrLoadModule()` or `server.ssrFixStacktrace()`; invoke `server.environments[name].runner.runModule()` or `server.environments[name].runner.import()` instead.
- Code executing in the `workerd` or `edge` environment MUST NOT import Node.js built-ins (`node:fs`, `node:path`, `node:child_process`) unless explicitly shimmed or aliased for that specific environment.
- Plugins targeting multiple environments MUST use per-environment hook definitions (`applyToEnvironment(environment)` or inspect `this.environment.name`) to enforce deterministic compilation paths.
- Services MUST define explicit, non-overlapping `resolve.conditions` for each runtime environment (e.g., `['workerd', 'worker']` vs `['node', 'import']` vs `['browser']`).

## Bad vs Good Implementations
### Multi-Runtime Environment Configuration with Isolated Conditions

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring runtimes via legacy `ssr` flags and global `resolve.conditions` causes export condition cross-contamination, causing Node.js or browser-specific modules to leak into Cloudflare workerd/edge runtimes. The plugin cache is shared globally across runtimes without environment scoping.
```typescript
import { defineConfig } from 'vite';

// Anti-pattern: Monolithic config with overlapping SSR flags
// Leaks Node.js resolution into workerd and relies on global ssr condition
export default defineConfig({
  ssr: {
    target: 'webworker',
    noExternal: true,
  },
  resolve: {
    // Problematic: global conditions leak across client and server
    conditions: ['workerd', 'browser', 'node'],
  },
  plugins: [
    {
      name: 'leaky-cache-plugin',
      transform(code, id) {
        // Problematic: shared memory cache across runtimes
        globalTransformCache.set(id, code);
        return code;
      },
    },
  ],
});
```

#### Production Standard (Correct)
> **Standard**: Uses the Vite 6 `environments` API to strictly sandbox `client`, `workerd`, and `node` runtimes with isolated `resolve.conditions` and `consumer` roles. Plugin hooks scope cached artifacts by `this.environment.name` to prevent cross-runtime contamination.
```typescript
import { defineConfig } from 'vite';

const environmentScopedCache = new Map<string, Map<string, string>>();

export default defineConfig({
  environments: {
    client: {
      resolve: {
        conditions: ['browser', 'module'],
      },
      consumer: 'client',
    },
    workerd: {
      resolve: {
        conditions: ['workerd', 'worker', 'import'],
        external: ['cloudflare:workers'],
      },
      consumer: 'server',
    },
    node: {
      resolve: {
        conditions: ['node', 'import'],
      },
      consumer: 'server',
    },
  },
  plugins: [
    {
      name: 'isolated-runtime-plugin',
      transform(code, id) {
        const envName = this.environment.name;
        if (!environmentScopedCache.has(envName)) {
          environmentScopedCache.set(envName, new Map());
        }
        const envCache = environmentScopedCache.get(envName)!;
        envCache.set(id, code);
        return code;
      },
    },
  ],
});
```

### Programmatic Module Execution via Environment Runner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `server.ssrLoadModule` forces execution through the default Node.js SSR runtime, completely bypassing custom environment runtimes (like edge or workerd) and breaking module sandboxing.
```typescript
import type { ViteDevServer } from 'vite';

// Anti-pattern: Invoking deprecated server.ssrLoadModule
// Ignores target environment sandboxes and defaults unconditionally to Node ssr
export async function executeHandler(server: ViteDevServer, entryUrl: string) {
  const mod = await server.ssrLoadModule(entryUrl);
  return mod.default;
}
```

#### Production Standard (Correct)
> **Standard**: Uses Vite 6's `server.environments[name].runner.import()` to dynamically execute the module graph inside the exact, isolated execution context configured for that target runtime.
```typescript
import type { ViteDevServer } from 'vite';

export async function executeHandler(
  server: ViteDevServer,
  environmentName: 'node' | 'workerd',
  entryUrl: string
) {
  const environment = server.environments[environmentName];
  if (!environment) {
    throw new Error(`Environment '${environmentName}' is not configured in Vite server.`);
  }

  // Vite 6: Execute within the isolated runtime runner of the specified environment
  const mod = await environment.runner.import(entryUrl);
  return mod.default;
}
```

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 Standard

Vite 6 Environment API Multi-Runtime Module Sandboxing Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict runtime boundary isolation when cross-compiling shared libraries across browser, edge, Node.js, and workerd targets within a single Vite 6 dev server instance. Guarantees that module graphs, resolve conditions, and transform pipelines remain sandboxed to prevent runtime global contamination and invalid target execution. 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 module graphs and resolve conditions across browser, workerd, and Node.js runtimes using legacy single-target Vite paradigms. 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 module graphs and resolve conditions across browser, workerd, and Node.js runtimes using legacy single-target Vite paradigms.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

Engineers MUST ALWAYS configure runtime targets using the Vite 6 top-level `environments` configuration key instead of legacy overloaded `ssr` or conditional plugin arrays.

Engineers MUST ALWAYS configure runtime targets using the Vite 6 top-level `environments` configuration key instead of legacy overloaded `ssr` or conditional plugin arrays.

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 ALWAYS qualify plugin caches and transform states with `this.environment.name` inside Vite plugin hooks to prevent cross-runtime AST or bytecode leakage.

Engineers MUST ALWAYS qualify plugin caches and transform states with `this.environment.name` inside Vite plugin hooks to prevent cross-runtime AST or bytecode leakage.

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 `server.ssrLoadModule()` or `server.ssrFixStacktrace()`

Engineers MUST NOT use deprecated `server.ssrLoadModule()` or `server.ssrFixStacktrace()`; invoke `server.environments[name].runner.runModule()` or `server.environments[name].runner.import()` instead.

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

Code executing in the `workerd` or `edge` environment MUST NOT import Node.js built-ins (`node

Code executing in the `workerd` or `edge` environment MUST NOT import Node.js built-ins (`node:fs`, `node:path`, `node:child_process`) unless explicitly shimmed or aliased for that specific environment.

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 per-environment hook definitions (`applyToEnvironment(environment)` or inspect `this.environment.name`) to enforce deterministic compilation paths.

Plugins targeting multiple environments MUST use per-environment hook definitions (`applyToEnvironment(environment)` or inspect `this.environment.name`) to enforce deterministic compilation paths.

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

Services MUST define explicit, non-overlapping `resolve.conditions` for each runtime environment (e.g., `['workerd', 'worker']` vs `['node', 'import']` vs `['browser']`).

Services MUST define explicit, non-overlapping `resolve.conditions` for each runtime environment (e.g., `['workerd', 'worker']` vs `['node', 'import']` vs `['browser']`).

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

Enforces strict runtime boundary isolation when cross-compiling shared libraries across browser, edge, Node.js, and workerd targets within a single Vite 6 dev server instance. Guarantees that module graphs, resolve conditions, and transform pipelines remain sandboxed to prevent runtime global contamination and invalid target execution. 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 module graphs and resolve conditions across browser, workerd, and Node.js runtimes using legacy single-target Vite paradigms.) 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