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-isolation-standard

Vite 6 Environment API Multi-Runtime Sandbox Isolation Standard

Enforces strict boundary separation across Vite 6 environments (client, ssr, edge, workerd) to prevent cross-runtime module graph pollution, unauthorized Node.js built-in leakage, and environment-mismatched bundle poisoning. Mandates programmatic isolation via Vite 6 Environment API configurations, environment-scoped plugin hooks, and explicit package export condition targeting.

Prohibited Anti-Pattern: Cross-Runtime Module Graph Leaks and Monolithic Plugin State Poisoning

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime Sandbox Isolation Standard - Enforces strict boundary separation across Vite 6 environments (client, ssr, edge, workerd) to prevent cross-runtime module graph pollution, unauthorized Node.js built-in leakage, and environment-mismatched bundle poisoning. Mandates programmatic isolation via Vite 6 Environment API configurations, environment-scoped plugin hooks, and explicit package export condition targeting.
globs: vite.config.{ts,js,mjs}, src/**/*.{ts,tsx}, plugins/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-environment-api-runtime-isolation-standard"
---

# Vite 6 Environment API Multi-Runtime Sandbox Isolation Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Runtime Module Graph Leaks and Monolithic Plugin State Poisoning

## System Constraints
You are a Principal Engineer enforcing the Vite 6 Environment API Multi-Runtime Sandbox Isolation Standard. You must mandate strict physical and logical boundaries between distinct execution runtimes (client, SSR, workerd/edge). Ensure that all Vite configurations declare explicit environment instances using the Vite 6 `environments` API rather than legacy global configuration hacks. Prevent node built-in contamination in browser/edge bundles, isolate transform caches per environment, and require plugin hooks to respect `this.environment` context.

## Strict Guidelines
- Engineers MUST ALWAYS configure multi-runtime builds using Vite 6 `environments` record (`client`, `ssr`, `edge`, etc.) rather than top-level legacy SSR options or multi-process workarounds.
- Engineers MUST NEVER access shared mutable plugin state across environments; plugins MUST scope cache and metadata stores by `this.environment.name`.
- Code targeting non-Node environments (such as `edge` or `client`) MUST NOT resolve or import `node:*` primitives without explicit polyfills or environment-scoped fallbacks.
- Services MUST define explicit `resolve.conditions` per environment (e.g., `['browser']`, `['node']`, `['workerd', 'worker']`) to guarantee deterministic package export resolution.
- Components NEVER import server-only or edge-only execution handles in modules marked for client environment bundling without compile-time runtime dead-code elimination.

## Bad vs Good Implementations
### Vite 6 Multi-Environment Configuration Sandbox

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using legacy top-level SSR flags and mutable process.env state creates a single, entangled module graph where resolution conditions collide, risking Node runtime leakage into browser/edge output and breaking Vite 6 dev server environment multiplexing.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Legacy monolithic config mixing SSR and Client
// Allows Node.js built-ins to leak into client bundles and shares global resolve state
export default defineConfig({
  build: {
    ssr: process.env.IS_SSR ? 'src/entry-server.ts' : false,
    outDir: process.env.IS_SSR ? 'dist/server' : 'dist/client'
  },
  resolve: {
    // Shared conditions cause resolution collisions between Edge and Node
    conditions: ['node', 'import']
  }
});
```

#### Production Standard (Correct)
> **Standard**: Explicitly declares decoupled client, ssr, and edge environments under the Vite 6 `environments` API, maintaining isolated resolution conditions and dedicated module graphs for each target runtime.
```typescript
import { defineConfig } from 'vite';

// PRODUCTION FIX: Explicit Vite 6 Environment API configuration
export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client'
      },
      resolve: {
        conditions: ['browser'],
        noExternal: false
      }
    },
    ssr: {
      build: {
        outDir: 'dist/server',
        ssr: true
      },
      resolve: {
        conditions: ['node']
      }
    },
    edge: {
      build: {
        outDir: 'dist/edge',
        ssr: true
      },
      resolve: {
        conditions: ['workerd', 'worker']
      }
    }
  }
});
```

### Environment-Aware Vite 6 Plugin Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Shared Set memory pollutes cache across environments. The plugin does not inspect `this.environment`, potentially false-flagging legitimate Node SSR modules or ignoring leaks across the client boundary.
```typescript
import type { Plugin } from 'vite';

// ANTI-PATTERN: Shared global module cache across all runtimes
const transformedModules = new Set<string>();

export function leakDetectionPlugin(): Plugin {
  return {
    name: 'leak-detection',
    transform(code, id) {
      if (transformedModules.has(id)) {
        return;
      }
      transformedModules.add(id);
      // Blindly checks code without knowing target environment
      if (code.includes('node:fs')) {
        console.warn(`Found node:fs in ${id}`);
      }
      return code;
    }
  };
}
```

#### Production Standard (Correct)
> **Standard**: Accesses `this.environment.name` to isolate transformed caches per environment and raises a fatal compile-time diagnostic if Node.js primitives leak into client or edge worker module graphs.
```typescript
import type { Plugin } from 'vite';

// PRODUCTION FIX: Scoped state per Vite 6 environment instance
export function leakDetectionPlugin(): Plugin {
  const envCaches = new Map<string, Set<string>>();

  return {
    name: 'leak-detection',
    transform(code, id) {
      const envName = this.environment.name;
      
      if (!envCaches.has(envName)) {
        envCaches.set(envName, new Set());
      }
      
      const cache = envCaches.get(envName)!;
      if (cache.has(id)) {
        return null;
      }
      cache.add(id);

      // Enforce strict runtime isolation based on current environment
      if ((envName === 'client' || envName === 'edge') && /['"]node:[a-z]+['"]/.test(code)) {
        this.error(
          `[Sandbox Violation] Node.js primitive imported in '${envName}' environment: ${id}`
        );
      }

      return null;
    }
  };
}
```

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 Sandbox Isolation Standard

Vite 6 Environment API Multi-Runtime Sandbox Isolation Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary separation across Vite 6 environments (client, ssr, edge, workerd) to prevent cross-runtime module graph pollution, unauthorized Node.js built-in leakage, and environment-mismatched bundle poisoning. Mandates programmatic isolation via Vite 6 Environment API configurations, environment-scoped plugin hooks, and explicit package export condition targeting. 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 Leaks and Monolithic Plugin State Poisoning 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 Leaks and Monolithic Plugin State PoisoningCritical
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 multi-runtime builds using Vite 6 `environments` record (`client`, `ssr`, `edge`, etc.) rather than top-level legacy SSR options or multi-process workarounds.

Engineers MUST ALWAYS configure multi-runtime builds using Vite 6 `environments` record (`client`, `ssr`, `edge`, etc.) rather than top-level legacy SSR options or multi-process workarounds.

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 NEVER access shared mutable plugin state across environments

Engineers MUST NEVER access shared mutable plugin state across environments; plugins MUST scope cache and metadata stores by `this.environment.name`.

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 targeting non-Node environments (such as `edge` or `client`) MUST NOT resolve or import `node

Code targeting non-Node environments (such as `edge` or `client`) MUST NOT resolve or import `node:*` primitives without explicit polyfills or environment-scoped fallbacks.

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 MUST define explicit `resolve.conditions` per environment (e.g., `['browser']`, `['node']`, `['workerd', 'worker']`) to guarantee deterministic package export resolution.

Services MUST define explicit `resolve.conditions` per environment (e.g., `['browser']`, `['node']`, `['workerd', 'worker']`) to guarantee deterministic package export resolution.

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

Components NEVER import server-only or edge-only execution handles in modules marked for client environment bundling without compile-time runtime dead-code elimination.

Components NEVER import server-only or edge-only execution handles in modules marked for client environment bundling without compile-time runtime dead-code elimination.

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

Enforces strict boundary separation across Vite 6 environments (client, ssr, edge, workerd) to prevent cross-runtime module graph pollution, unauthorized Node.js built-in leakage, and environment-mismatched bundle poisoning. Mandates programmatic isolation via Vite 6 Environment API configurations, environment-scoped plugin hooks, and explicit package export condition targeting. 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 Leaks and Monolithic Plugin State Poisoning) 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