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

Vite 6 Environment API Cross-Runtime Artifact Isolation Guardrail

Enforces strict module graph boundary isolation across client, Node SSR, and Edge Worker targets using the Vite 6 Environment API. Prevents tree-shake poisoning, secret leakage, and incompatible runtime symbol resolution by enforcing isolated module resolve conditions, separate dependency pipelines, and compile-time boundary validation.

Prohibited Anti-Pattern: Cross-Runtime Graph Contamination and Tree-Shake Poisoning via Monolithic Module Bundling

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Cross-Runtime Artifact Isolation Guardrail - Enforces strict module graph boundary isolation across client, Node SSR, and Edge Worker targets using the Vite 6 Environment API. Prevents tree-shake poisoning, secret leakage, and incompatible runtime symbol resolution by enforcing isolated module resolve conditions, separate dependency pipelines, and compile-time boundary validation.
globs: vite.config.{ts,js,mjs}, src/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-cross-runtime-isolation-vite-6-environme-854"
---

# Vite 6 Environment API Cross-Runtime Artifact Isolation Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Runtime Graph Contamination and Tree-Shake Poisoning via Monolithic Module Bundling

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API Cross-Runtime Artifact Isolation. You must mandate zero leakage between client, SSR, and edge environments. Ensure all multi-target pipelines utilize distinct Vite 6 Environment configurations with hermetic module resolution, strict export conditions, and compile-time isolation barriers.

## Strict Guidelines
- Engineers MUST ALWAYS configure target runtimes using Vite 6's top-level `environments` configuration block rather than legacy monolithic plugins or ad-hoc SSR build flags.
- Engineers MUST configure distinct `resolve.conditions` for each environment (e.g., `['browser']` for client, `['node', 'node-addons']` for ssr, and `['workerd', 'worker']` for edge).
- Engineers MUST NOT allow cross-environment imports from boundary-crossing entry points or shared barrel files without explicit `.client.ts`, `.server.ts`, or `.edge.ts` module splits.
- Code SHOULD leverage Vite 6 Module Runner APIs (`createServerModuleRunner`) for decoupled SSR execution instead of legacy `ssrLoadModule`.
- Components NEVER import node-native modules (`node:crypto`, `node:fs`, `node:async_hooks`) directly into common utility trees that resolve into the client environment graph.
- Vite plugins targeting specific runtimes MUST specify `applyToEnvironment(environment)` to guarantee execution only inside the intended environment lifecycle.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: A monolithic config mixing conditions allows bundler branch-elimination failures where Node or Worker dependencies are resolved into client chunks, causing runtime crashes and potential secret leakage.
```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// ANTI-PATTERN: Monolithic SSR/Client config relying on legacy flags and unified resolution.
// Edge and Client targets share common resolve conditions, allowing Node/Edge symbols to leak into browser chunks.
export default defineConfig({
  plugins: [react()],
  build: {
    ssr: process.env.IS_SSR ? 'src/entry-server.tsx' : false,
    outDir: process.env.IS_SSR ? 'dist/server' : 'dist/client'
  },
  resolve: {
    // Universal conditions poison client bundles with node-specific module branches
    conditions: ['node', 'browser', 'workerd']
  }
});
```

#### Production Standard (Correct)
> **Standard**: Defines explicit Vite 6 environment instances with separated `resolve.conditions`, preventing cross-environment package poisoning and ensuring each graph is processed with its native target requirements.
```typescript
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

// PRODUCTION STANDARD: Vite 6 Environment API with hermetic runtime boundaries.
export default defineConfig({
  plugins: [react()],
  environments: {
    client: {
      build: {
        outDir: 'dist/client',
        manifest: true
      },
      resolve: {
        conditions: ['browser'],
        noExternal: false
      }
    },
    ssr: {
      build: {
        outDir: 'dist/server',
        ssr: 'src/entry-server.tsx'
      },
      resolve: {
        conditions: ['node'],
        external: ['node:*']
      }
    },
    edge: {
      build: {
        outDir: 'dist/edge',
        ssr: 'src/entry-edge.ts'
      },
      resolve: {
        conditions: ['workerd', 'worker'],
        noExternal: true
      }
    }
  }
});
```

### Runtime Boundary Split Pattern for Shared Modules

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relying on runtime branching (`typeof window === 'undefined'`) inside a unified file forces bundlers to evaluate `node:crypto`, failing client tree-shaking and throwing module not found errors.
```typescript
// src/utils/session.ts
// ANTI-PATTERN: Direct runtime mixing in shared barrel/utility module
import crypto from 'node:crypto';

export interface Session {
  id: string;
}

export function createSessionId(): string {
  // Crashes in client bundle when tree-shaking fails or runtime is browser
  if (typeof window === 'undefined') {
    return crypto.randomBytes(16).toString('hex');
  }
  return window.crypto.randomUUID();
}
```

#### Production Standard (Correct)
> **Standard**: Using environment-suffixed files paired with environment-specific alias mapping or package exports completely isolates platform-specific implementations into discrete module graphs.
```typescript
// src/utils/session.client.ts
export function createSessionId(): string {
  return window.crypto.randomUUID();
}

// src/utils/session.server.ts
import { randomBytes } from 'node:crypto';
export function createSessionId(): string {
  return randomBytes(16).toString('hex');
}

// src/utils/session.edge.ts
export function createSessionId(): string {
  return crypto.randomUUID();
}
```

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 Cross-Runtime Artifact Isolation Guardrail

Vite 6 Environment API Cross-Runtime Artifact Isolation Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces strict module graph boundary isolation across client, Node SSR, and Edge Worker targets using the Vite 6 Environment API. Prevents tree-shake poisoning, secret leakage, and incompatible runtime symbol resolution by enforcing isolated module resolve conditions, separate dependency pipelines, and compile-time boundary validation. 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 Graph Contamination and Tree-Shake Poisoning via Monolithic Module Bundling 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 Graph Contamination and Tree-Shake Poisoning via Monolithic Module BundlingCritical
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 target runtimes using Vite 6's top-level `environments` configuration block rather than legacy monolithic plugins or ad-hoc SSR build flags.

Engineers MUST ALWAYS configure target runtimes using Vite 6's top-level `environments` configuration block rather than legacy monolithic plugins or ad-hoc SSR build 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.
2

Engineers MUST configure distinct `resolve.conditions` for each environment (e.g., `['browser']` for client, `['node', 'node-addons']` for ssr, and `['workerd', 'worker']` for edge).

Engineers MUST configure distinct `resolve.conditions` for each environment (e.g., `['browser']` for client, `['node', 'node-addons']` for ssr, and `['workerd', 'worker']` for edge).

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 allow cross-environment imports from boundary-crossing entry points or shared barrel files without explicit `.client.ts`, `.server.ts`, or `.edge.ts` module splits.

Engineers MUST NOT allow cross-environment imports from boundary-crossing entry points or shared barrel files without explicit `.client.ts`, `.server.ts`, or `.edge.ts` module splits.

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 SHOULD leverage Vite 6 Module Runner APIs (`createServerModuleRunner`) for decoupled SSR execution instead of legacy `ssrLoadModule`.

Code SHOULD leverage Vite 6 Module Runner APIs (`createServerModuleRunner`) for decoupled SSR execution instead of legacy `ssrLoadModule`.

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 node-native modules (`node

Components NEVER import node-native modules (`node:crypto`, `node:fs`, `node:async_hooks`) directly into common utility trees that resolve into the client environment graph.

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

Vite plugins targeting specific runtimes MUST specify `applyToEnvironment(environment)` to guarantee execution only inside the intended environment lifecycle.

Vite plugins targeting specific runtimes MUST specify `applyToEnvironment(environment)` to guarantee execution only inside the intended environment lifecycle.

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 Cross-Runtime Artifact Isolation Guardrail critical for AI coding assistants?

Enforces strict module graph boundary isolation across client, Node SSR, and Edge Worker targets using the Vite 6 Environment API. Prevents tree-shake poisoning, secret leakage, and incompatible runtime symbol resolution by enforcing isolated module resolve conditions, separate dependency pipelines, and compile-time boundary validation. 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 Graph Contamination and Tree-Shake Poisoning via Monolithic Module Bundling) 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