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

Vite 6 Environment API Multi-Runtime Target Sandboxing & Isolation

Enforces strict runtime boundary isolation using the Vite 6 Environment API across heterogeneous deployment targets (Node.js, Bun, workerd). Eliminates cross-runtime polyfill pollution, prevents global scope contamination, and ensures deterministic per-environment module resolution and execution pipelines.

Prohibited Anti-Pattern: Monolithic SSR Configuration and Global Runtime Polyfill Leakage Across Node, Bun, and Edge Targets

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime Target Sandboxing & Isolation - Enforces strict runtime boundary isolation using the Vite 6 Environment API across heterogeneous deployment targets (Node.js, Bun, workerd). Eliminates cross-runtime polyfill pollution, prevents global scope contamination, and ensures deterministic per-environment module resolution and execution pipelines.
globs: vite.config.ts, vite.config.mts, src/entry-*.ts, src/server/**/*.{ts,tsx}, src/runtimes/**/*.{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-environme-851"
---

# Vite 6 Environment API Multi-Runtime Target Sandboxing & Isolation

> **Severity**: CRITICAL | **Category**: devops
> **Anti-Pattern Warning**: Monolithic SSR Configuration and Global Runtime Polyfill Leakage Across Node, Bun, and Edge Targets

## System Constraints
You are a Principal DevOps and Build Infrastructure Architect enforcing strict target-specific sandboxing with the Vite 6 Environment API. Mandate discrete module graphs, runtime-specific export conditions, isolated runner instances, and zero global polyfill leaks across universal SSR applications targeting Node.js, Bun, and workerd.

## Strict Guidelines
- Engineers MUST ALWAYS declare isolated runtime targets under `environments` in `vite.config.ts` using Vite 6's Environment API instead of relying on legacy top-level `ssr` configurations.
- Engineers MUST configure distinct `resolve.conditions` per environment (e.g., `['workerd', 'worker']` for edge vs `['node', 'import']` for Node.js) to prevent Node built-ins from entering worker bundles.
- Engineers MUST NOT inject unscoped polyfills into universal source modules or mutate `globalThis` globally; shims must be applied strictly via per-environment injected entrypoints or runner shims.
- Vite plugins MUST implement environment-aware hooks (`configEnvironment`, `hotUpdate`, `transform`) checking `this.environment.name` instead of applying universal transforms across all targets.
- Shared universal library code NEVER imports runtime-specific built-ins (`node:fs`, `node:async_hooks`, `Bun.serve`) without export-map separation or explicit runtime detection abstractions.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: A single monolithic `ssr` configuration leaks conflicting export conditions (`workerd` and `node`), causing non-deterministic package resolution. Top-level `define` directives globally contaminate client and edge runtimes with Node.js primitives.
```typescript
// vite.config.ts: Legacy Vite 5 monolithic SSR setup causing condition leaks and polyfill bleeding
import { defineConfig } from 'vite';

export default defineConfig({
  ssr: {
    // Pollutes resolution for both Node and workerd targets
    target: 'node',
    noExternal: true,
    resolve: {
      conditions: ['workerd', 'node', 'import'] // Ambiguous: workerd packages resolve Node fallbacks
    }
  },
  define: {
    // Global pollution leaking into all client and edge bundles
    'process.env.RUNTIME': JSON.stringify('universal'),
    'global.Buffer': 'Buffer'
  }
});
```

#### Production Standard (Correct)
> **Standard**: Defines discrete environments using the Vite 6 Environment API. Node and Edge (workerd) maintain separate resolution conditions, externalization rules, and output directories, completely eliminating cross-runtime polyfill bleed.
```typescript
// vite.config.ts: Vite 6 Environment API configuration with strict runtime isolation
import { defineConfig } from 'vite';

export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client'
      }
    },
    node: {
      resolve: {
        conditions: ['node', 'import', 'module'],
        external: true
      },
      build: {
        outDir: 'dist/node',
        target: 'node20'
      }
    },
    edge: {
      resolve: {
        conditions: ['workerd', 'worker', 'browser'],
        noExternal: true // Must inline for edge runtime isolation
      },
      build: {
        outDir: 'dist/edge',
        target: 'esnext'
      }
    }
  },
  builder: {
    async buildApp(builder) {
      // Deterministic and isolated builds per target environment
      await builder.build(builder.environments.client);
      await builder.build(builder.environments.node);
      await builder.build(builder.environments.edge);
    }
  }
});
```

### Environment-Aware Custom Vite Plugin Hook

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Applies a universal code transformation regardless of which environment is being compiled, forcing heavy Node shims into lightweight Cloudflare Worker or client-side bundles.
```typescript
// plugins/runtime-inject.ts: Naive plugin polluting all environments indiscriminately
import type { Plugin } from 'vite';

export function runtimeInjectPlugin(): Plugin {
  return {
    name: 'runtime-inject',
    transform(code, id) {
      // Injects Node polyfill into ALL files across client, node, and workerd
      return `import 'node-stdlib-browser/proxy';\n${code}`;
    }
  };
};
```

#### Production Standard (Correct)
> **Standard**: Leverages Vite 6's `configEnvironment` and inspects `this.environment.name` in hook contexts to guarantee transformations are strictly sandboxed to the target runtime.
```typescript
// plugins/runtime-inject.ts: Vite 6 Environment-aware plugin lifecycle
import type { Plugin } from 'vite';

export function runtimeInjectPlugin(): Plugin {
  return {
    name: 'runtime-inject',
    // Vite 6 hook to configure environment-specific settings
    configEnvironment(name, config) {
      if (name === 'edge') {
        return {
          resolve: {
            conditions: ['workerd']
          }
        };
      }
    },
    transform(code, id) {
      // Strictly scope transform logic to the intended environment
      if (this.environment.name !== 'node') {
        return null;
      }
      // Only apply Node-specific instrumentation to the Node environment
      return code;
    }
  };
};
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Vite 6 Environment API Multi-Runtime Target Sandboxing & Isolation

Vite 6 Environment API Multi-Runtime Target Sandboxing & Isolation defines an industrial-grade behavioral standard for devops engineering. Enforces strict runtime boundary isolation using the Vite 6 Environment API across heterogeneous deployment targets (Node.js, Bun, workerd). Eliminates cross-runtime polyfill pollution, prevents global scope contamination, and ensures deterministic per-environment module resolution and execution 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: Monolithic SSR Configuration and Global Runtime Polyfill Leakage Across Node, Bun, and Edge Targets 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 DriftMonolithic SSR Configuration and Global Runtime Polyfill Leakage Across Node, Bun, and Edge TargetsCritical
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 declare isolated runtime targets under `environments` in `vite.config.ts` using Vite 6's Environment API instead of relying on legacy top-level `ssr` configurations.

Engineers MUST ALWAYS declare isolated runtime targets under `environments` in `vite.config.ts` using Vite 6's Environment API instead of relying on legacy top-level `ssr` configurations.

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` per environment (e.g., `['workerd', 'worker']` for edge vs `['node', 'import']` for Node.js) to prevent Node built-ins from entering worker bundles.

Engineers MUST configure distinct `resolve.conditions` per environment (e.g., `['workerd', 'worker']` for edge vs `['node', 'import']` for Node.js) to prevent Node built-ins from entering worker bundles.

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 inject unscoped polyfills into universal source modules or mutate `globalThis` globally

Engineers MUST NOT inject unscoped polyfills into universal source modules or mutate `globalThis` globally; shims must be applied strictly via per-environment injected entrypoints or runner shims.

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

Vite plugins MUST implement environment-aware hooks (`configEnvironment`, `hotUpdate`, `transform`) checking `this.environment.name` instead of applying universal transforms across all targets.

Vite plugins MUST implement environment-aware hooks (`configEnvironment`, `hotUpdate`, `transform`) checking `this.environment.name` instead of applying universal transforms across all targets.

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

Shared universal library code NEVER imports runtime-specific built-ins (`node

Shared universal library code NEVER imports runtime-specific built-ins (`node:fs`, `node:async_hooks`, `Bun.serve`) without export-map separation or explicit runtime detection abstractions.

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

Enforces strict runtime boundary isolation using the Vite 6 Environment API across heterogeneous deployment targets (Node.js, Bun, workerd). Eliminates cross-runtime polyfill pollution, prevents global scope contamination, and ensures deterministic per-environment module resolution and execution 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 (Monolithic SSR Configuration and Global Runtime Polyfill Leakage Across Node, Bun, and Edge Targets) 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

Vite