This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
devopscritical PriorityID: vite-6-rolldown-environment-api-ssr-module-isolation

Deterministic Environment Module Isolation & Dual-Package Boundary Guardrail

Enforces complete module graph partitioning and prevents dual-package hazards across client, SSR, and edge runtimes via the Vite 6 / Rolldown Environment API. Guarantees that server-only bindings, platform primitives, and dual ESM/CJS runtime singletons remain strictly isolated within designated execution boundaries without cross-graph pollution or invalid runtime shims.

Prohibited Anti-Pattern: Cross-Environment Graph Leakage and Dual-Package Singleton Collisions via Monolithic Vite Configs

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Environment Module Isolation & Dual-Package Boundary Guardrail - Enforces complete module graph partitioning and prevents dual-package hazards across client, SSR, and edge runtimes via the Vite 6 / Rolldown Environment API. Guarantees that server-only bindings, platform primitives, and dual ESM/CJS runtime singletons remain strictly isolated within designated execution boundaries without cross-graph pollution or invalid runtime shims.
globs: vite.config.{ts,js,mjs}, src/entry-server.{ts,tsx,js}, src/entry-client.{ts,tsx,js}, src/server/**/*.{ts,tsx}, src/**/*.{server,client}.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-rolldown-environment-api-ssr-module-isolation"
---

# Deterministic Environment Module Isolation & Dual-Package Boundary Guardrail

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Cross-Environment Graph Leakage and Dual-Package Singleton Collisions via Monolithic Vite Configs

## System Constraints
You are a Principal Architect enforcing strict runtime module isolation using Vite 6 and Rolldown Environment APIs. You must reject legacy top-level SSR configurations (`ssr: true`, top-level `ssr.external`, and universal alias injection) that breach execution boundary invariants. Mandate per-environment configuration blocks (`environments.client`, `environments.ssr`, `environments.edge`), isolate dual-package dependencies by explicitly mapping condition names and resolve targets, and eliminate cross-runtime singleton leaks.

## Strict Guidelines
- Engineers MUST ALWAYS configure isolated environments via Vite 6's `environments` configuration block (`environments.client`, `environments.ssr`, and custom runtimes like `environments.edge`) rather than relying on global `ssr` root-level flags.
- Engineers MUST NOT allow dual-package hazard candidates (packages maintaining state singletons like React, GraphQL, or OpenTelemetry) to be resolved simultaneously through divergent formats (CJS vs ESM) across environment boundaries; explicit `resolve.conditions` and `resolve.externalConditions` MUST be specified per environment.
- Plugins targeting environment-specific hooks MUST inspect `this.environment.name` or leverage `perEnvironmentPlugin` wrappers to prevent injecting browser transforms into SSR or Edge module graphs.
- Custom dev servers MUST instantiate separate runtime runners per environment via `server.environments[name].runner` rather than evaluating SSR entries directly against the default module graph using `ssrLoadModule`.
- Components and utilities executing in the edge environment MUST explicitly declare `resolve.noExternal` for Node.js built-ins or leverage dedicated unenv/workerd polyfill maps within `environments.edge.resolve` to prevent unresolved external bindings at runtime.

## Bad vs Good Implementations
### Migrating Monolithic Legacy SSR Config to Vite 6 Environment API with Dual-Package Guardrails

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Applying resolve conditions globally forces the SSR runner to resolve browser-targeted subpath exports, leading to missing Node.js runtime bindings. Conversely, unpartitioned external arrays trigger dual-package hazards where CJS and ESM versions of stateful libraries load simultaneously in the same process.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Root-level SSR config shares graph resolution and aliases across runtimes,
// creating dual-package hazards (e.g., duplicate React contexts) and cross-runtime boundary leaks.
export default defineConfig({
  ssr: {
    noExternal: ['lodash-es', 'react-router'],
    external: ['node:async_hooks'],
  },
  resolve: {
    // Universal conditions applied indiscriminately to both client and server graphs
    conditions: ['import', 'browser'],
  },
  build: {
    ssr: 'src/entry-server.ts',
  }
});
```

#### Production Standard (Correct)
> **Standard**: By explicitly declaring isolated configurations under `environments`, each runtime graph (client, SSR Node, edge worker) resolves its own package entry conditions and externals deterministically, completely eliminating dual-package singleton hazards and unmapped runtime imports.
```typescript
import { defineConfig } from 'vite';

// PRODUCTION INVARIANT: Complete graph isolation via Vite 6 Environment API
export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client',
      },
      resolve: {
        conditions: ['browser', 'import', 'module', 'default'],
      },
    },
    ssr: {
      build: {
        outDir: 'dist/ssr',
        ssr: true,
      },
      resolve: {
        conditions: ['node', 'import', 'module', 'default'],
        externalConditions: ['node'],
        noExternal: ['react-router'], // Bundled into SSR graph as ESM
        external: ['node:async_hooks'],
      },
    },
    edge: {
      build: {
        outDir: 'dist/edge',
        ssr: true,
      },
      resolve: {
        conditions: ['edge-light', 'worker', 'import', 'default'],
        externalConditions: ['edge-light', 'worker'],
        noExternal: true, // Complete inlining: no Node runtime globals permitted
      },
    },
  },
});
```

### Strict Per-Environment Plugin Scoping to Prevent Cross-Graph AST Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The plugin does not evaluate the runtime environment context. When Vite 6 processes the SSR module graph, this transform mutates server-side code with client-specific identifiers (`window`), crashing the server renderer.
```typescript
import type { Plugin } from 'vite';

// ANTI-PATTERN: Hook runs indiscriminately across all environments
export function transformClientTelemetryPlugin(): Plugin {
  return {
    name: 'client-telemetry-transform',
    transform(code, id) {
      if (id.includes('telemetry.ts')) {
        // Injects window-dependent code into server graphs during SSR build
        return code.replace('__INITIAL_STATE__', 'window.__INIT__');
      }
    },
  };
}
```

#### Production Standard (Correct)
> **Standard**: Using `applyToEnvironment` ensures the transform hook is registered strictly within the client module graph pipeline, leaving the SSR and Edge runtime graphs unpolluted and hermetic.
```typescript
import type { Plugin } from 'vite';

// PRODUCTION INVARIANT: Environment-aware compilation boundary
export function transformClientTelemetryPlugin(): Plugin {
  return {
    name: 'client-telemetry-transform',
    // Apply only within the explicit 'client' environment graph
    applyToEnvironment(environment) {
      return environment.name === 'client';
    },
    transform(code, id) {
      if (id.includes('telemetry.ts')) {
        return {
          code: code.replace('__INITIAL_STATE__', 'window.__INIT__'),
          map: 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: Deterministic Environment Module Isolation & Dual-Package Boundary Guardrail

Deterministic Environment Module Isolation & Dual-Package Boundary Guardrail defines an industrial-grade behavioral standard for devops engineering. Enforces complete module graph partitioning and prevents dual-package hazards across client, SSR, and edge runtimes via the Vite 6 / Rolldown Environment API. Guarantees that server-only bindings, platform primitives, and dual ESM/CJS runtime singletons remain strictly isolated within designated execution boundaries without cross-graph pollution or invalid runtime shims. 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-Environment Graph Leakage and Dual-Package Singleton Collisions via Monolithic Vite Configs 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-Environment Graph Leakage and Dual-Package Singleton Collisions via Monolithic Vite ConfigsCritical
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 isolated environments via Vite 6's `environments` configuration block (`environments.client`, `environments.ssr`, and custom runtimes like `environments.edge`) rather than relying on global `ssr` root-level flags.

Engineers MUST ALWAYS configure isolated environments via Vite 6's `environments` configuration block (`environments.client`, `environments.ssr`, and custom runtimes like `environments.edge`) rather than relying on global `ssr` root-level 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 NOT allow dual-package hazard candidates (packages maintaining state singletons like React, GraphQL, or OpenTelemetry) to be resolved simultaneously through divergent formats (CJS vs ESM) across environment boundaries

Engineers MUST NOT allow dual-package hazard candidates (packages maintaining state singletons like React, GraphQL, or OpenTelemetry) to be resolved simultaneously through divergent formats (CJS vs ESM) across environment boundaries; explicit `resolve.conditions` and `resolve.externalConditions` MUST be specified per 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.
3

Plugins targeting environment-specific hooks MUST inspect `this.environment.name` or leverage `perEnvironmentPlugin` wrappers to prevent injecting browser transforms into SSR or Edge module graphs.

Plugins targeting environment-specific hooks MUST inspect `this.environment.name` or leverage `perEnvironmentPlugin` wrappers to prevent injecting browser transforms into SSR or Edge 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.
4

Custom dev servers MUST instantiate separate runtime runners per environment via `server.environments[name].runner` rather than evaluating SSR entries directly against the default module graph using `ssrLoadModule`.

Custom dev servers MUST instantiate separate runtime runners per environment via `server.environments[name].runner` rather than evaluating SSR entries directly against the default module graph using `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 and utilities executing in the edge environment MUST explicitly declare `resolve.noExternal` for Node.js built-ins or leverage dedicated unenv/workerd polyfill maps within `environments.edge.resolve` to prevent unresolved external bindings at runtime.

Components and utilities executing in the edge environment MUST explicitly declare `resolve.noExternal` for Node.js built-ins or leverage dedicated unenv/workerd polyfill maps within `environments.edge.resolve` to prevent unresolved external bindings at runtime.

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 Deterministic Environment Module Isolation & Dual-Package Boundary Guardrail critical for AI coding assistants?

Enforces complete module graph partitioning and prevents dual-package hazards across client, SSR, and edge runtimes via the Vite 6 / Rolldown Environment API. Guarantees that server-only bindings, platform primitives, and dual ESM/CJS runtime singletons remain strictly isolated within designated execution boundaries without cross-graph pollution or invalid runtime shims. 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-Environment Graph Leakage and Dual-Package Singleton Collisions via Monolithic Vite Configs) 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.

1 Rule in Stack

Deterministic