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-boundary-standard-vite-6-environme-545

Vite 6 Environment API Cross-Runtime Module Boundary & AST Virtualization

Enforces strict hermetic AST virtualization and module isolation across concurrent Browser, Edge Worker (WinterCG), and Node.js SSR runtime execution targets via the Vite 6 Environment API. Eliminates architectural leaks caused by legacy binary SSR assumptions and prevents cross-contamination of runtime-specific module graphs.

Prohibited Anti-Pattern: Leaking Node.js Built-ins or Global Module Graph State into Edge and Client Runtimes via Legacy Binary SSR Assumptions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Cross-Runtime Module Boundary & AST Virtualization - Enforces strict hermetic AST virtualization and module isolation across concurrent Browser, Edge Worker (WinterCG), and Node.js SSR runtime execution targets via the Vite 6 Environment API. Eliminates architectural leaks caused by legacy binary SSR assumptions and prevents cross-contamination of runtime-specific module graphs.
globs: vite.config.{ts,js,mjs}, src/**/*.{ts,tsx,js,jsx}, plugins/**/*.{ts,js,mjs}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite-6-environment-api-runtime-boundary-standard-vite-6-environme-545"
---

# Vite 6 Environment API Cross-Runtime Module Boundary & AST Virtualization

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Leaking Node.js Built-ins or Global Module Graph State into Edge and Client Runtimes via Legacy Binary SSR Assumptions

## System Constraints
You are a Principal Software Architect enforcing the Vite 6 Environment API Cross-Runtime Module Boundary Standard. Vite 6 deprecates the monolithic binary `ssr: boolean` paradigm in favor of the formal `environments` configuration and `DevEnvironment` architecture. You must mandate strict hermetic module isolation, per-environment resolution conditions (e.g., WinterCG vs. Node vs. Browser), decoupled HMR event dispatching via `environment.hot`, and isolated Module Runner instances (`environment.runner.import`). Ensure no shared cross-runtime module graph leaks occur.

## Strict Guidelines
- Engineers MUST ALWAYS declare isolated runtime environments under `environments` (e.g., `client`, `ssr`, `edge`) in `vite.config.ts` rather than relying on legacy top-level `ssr` configuration flags.
- Engineers MUST NOT invoke deprecated `server.ssrLoadModule(entry)` or `server.ssrFixStacktrace`; instead, engineers MUST use `server.environments[envName].runner.import(entry)`.
- Vite plugin authors MUST inspect `this.environment.name` inside unified hooks (`resolveId`, `load`, `transform`) to isolate AST transforms per target runtime, and MUST NEVER rely on closure-shared mutable state across environments.
- Custom plugins MUST dispatch runtime-targeted events using `this.environment.hot.send()` instead of the global `server.hot.send()` to prevent cross-runtime HMR payload contamination.
- Resolution conditions MUST be explicitly configured per environment (e.g., `conditions: ['worker', 'wintercg']` for edge targets, `conditions: ['node']` for Node SSR targets, and `conditions: ['browser']` for client targets) to guarantee hermetic AST virtualization.
- Components and shared libraries NEVER import runtime-specific host modules (`node:fs`, `node:path`, `cloudflare:workers`) without runtime branch resolution guarded by environment module boundaries.

## Bad vs Good Implementations
### Vite 6 Multi-Environment Architecture vs Legacy SSR Config

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring SSR via monolithic top-level `ssr` settings forces all non-client environments to share identical condition names, externalization rules, and module evaluation contexts. This causes runtime crashes when targeting mixed Edge (WinterCG) and Node runtimes simultaneously.
```typescript
import { defineConfig } from 'vite';

// Anti-pattern: Vite 4/5 binary SSR assumption creates a monolithic module graph
// Node-specific built-ins and packages bleed into Edge or Cloudflare worker bundles
export default defineConfig({
  ssr: {
    noExternal: ['shared-ui', 'database-driver'],
    target: 'node'
  },
  build: {
    rollupOptions: {
      input: {
        client: 'src/entry-client.tsx',
        server: 'src/entry-server.tsx'
      }
    }
  }
});
```

#### Production Standard (Correct)
> **Standard**: Defines explicit, hermetically isolated environments (`client`, `edge`, `nodeSsr`). Each environment maintains independent resolution conditions, external module graphs, and distinct compilation lifecycles.
```typescript
import { defineConfig } from 'vite';

// Production Invariant: Hermetic Vite 6 Environment API configuration
export default defineConfig({
  environments: {
    client: {
      consumer: 'client',
      build: {
        outDir: 'dist/client',
        rollupOptions: { input: 'src/entry-client.tsx' }
      }
    },
    edge: {
      consumer: 'server',
      resolve: {
        conditions: ['worker', 'wintercg', 'import', 'browser'],
        noExternal: true
      },
      build: {
        outDir: 'dist/edge',
        rollupOptions: { input: 'src/entry-edge.ts' }
      }
    },
    nodeSsr: {
      consumer: 'server',
      resolve: {
        conditions: ['node', 'import', 'default'],
        external: ['pg', 'node:fs', 'node:path']
      },
      build: {
        outDir: 'dist/node',
        rollupOptions: { input: 'src/entry-node.ts' }
      }
    }
  }
});
```

### Custom Plugin Environment-Aware Transformation & Module Runner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The plugin uses closure state (`transformedCache`) across distinct runtimes, relies on the ambiguous binary `options.ssr` flag, and invokes deprecated Vite 5 `server.ssrLoadModule` and `server.hot.send`, which broadcast across all environments indiscriminately.
```typescript
import type { Plugin, ViteDevServer } from 'vite';

// Anti-pattern: Plugin shares global transform cache and uses deprecated ssrLoadModule
const transformedCache = new Map<string, string>();

export function brokenPlugin(): Plugin {
  let serverInstance: ViteDevServer;
  return {
    name: 'broken-cross-runtime-plugin',
    configureServer(server) {
      serverInstance = server;
    },
    transform(code, id, options) {
      // Flaw: Binary `options?.ssr` flag does not distinguish between Edge and Node SSR
      if (options?.ssr) {
        transformedCache.set(id, code);
      }
      return code;
    },
    async handleHotUpdate({ file }) {
      // Deprecated in Vite 6; pollutes global runner
      await serverInstance.ssrLoadModule(file);
      serverInstance.hot.send({ type: 'custom', event: 'reload' });
    }
  };
}
```

#### Production Standard (Correct)
> **Standard**: Leverages `this.environment.name`, `environment.runner.import`, and `environment.hot.send` to strictly confine transform checks, module loading, and HMR signals to the active runtime execution environment.
```typescript
import type { Plugin } from 'vite';

// Production Invariant: Environment-aware lifecycle execution
export function hermeticEnvironmentPlugin(): Plugin {
  return {
    name: 'hermetic-environment-plugin',
    transform(code, id) {
      // Use `this.environment.name` to isolate runtime-specific AST virtualization
      if (this.environment.name === 'edge') {
        if (code.includes('node:fs')) {
          this.error(`Forbidden Node.js built-in module referenced in Edge runtime: ${id}`);
        }
      }
      return null;
    },
    async hotUpdate({ modules, environment }) {
      // Environment-specific Module Runner execution and isolated HMR channel
      if (environment.name === 'nodeSsr') {
        for (const mod of modules) {
          if (mod.id) {
            await environment.runner.import(mod.id);
          }
        }
      }
      // Confine event dispatch strictly to the current environment
      environment.hot.send({
        type: 'custom',
        event: 'environment-updated',
        data: { env: environment.name }
      });
      return modules;
    }
  };
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Vite 6 Environment API Cross-Runtime Module Boundary & AST Virtualization

Vite 6 Environment API Cross-Runtime Module Boundary & AST Virtualization defines an industrial-grade behavioral standard for frontend engineering. Enforces strict hermetic AST virtualization and module isolation across concurrent Browser, Edge Worker (WinterCG), and Node.js SSR runtime execution targets via the Vite 6 Environment API. Eliminates architectural leaks caused by legacy binary SSR assumptions and prevents cross-contamination of runtime-specific module graphs. 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: Leaking Node.js Built-ins or Global Module Graph State into Edge and Client Runtimes via Legacy Binary SSR Assumptions 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 DriftLeaking Node.js Built-ins or Global Module Graph State into Edge and Client Runtimes via Legacy Binary SSR AssumptionsCritical
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 environments under `environments` (e.g., `client`, `ssr`, `edge`) in `vite.config.ts` rather than relying on legacy top-level `ssr` configuration flags.

Engineers MUST ALWAYS declare isolated runtime environments under `environments` (e.g., `client`, `ssr`, `edge`) in `vite.config.ts` rather than relying on legacy top-level `ssr` configuration 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 invoke deprecated `server.ssrLoadModule(entry)` or `server.ssrFixStacktrace`

Engineers MUST NOT invoke deprecated `server.ssrLoadModule(entry)` or `server.ssrFixStacktrace`; instead, engineers MUST use `server.environments[envName].runner.import(entry)`.

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

Vite plugin authors MUST inspect `this.environment.name` inside unified hooks (`resolveId`, `load`, `transform`) to isolate AST transforms per target runtime, and MUST NEVER rely on closure-shared mutable state across environments.

Vite plugin authors MUST inspect `this.environment.name` inside unified hooks (`resolveId`, `load`, `transform`) to isolate AST transforms per target runtime, and MUST NEVER rely on closure-shared mutable state across environments.

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 plugins MUST dispatch runtime-targeted events using `this.environment.hot.send()` instead of the global `server.hot.send()` to prevent cross-runtime HMR payload contamination.

Custom plugins MUST dispatch runtime-targeted events using `this.environment.hot.send()` instead of the global `server.hot.send()` to prevent cross-runtime HMR payload contamination.

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

Resolution conditions MUST be explicitly configured per environment (e.g., `conditions

Resolution conditions MUST be explicitly configured per environment (e.g., `conditions: ['worker', 'wintercg']` for edge targets, `conditions: ['node']` for Node SSR targets, and `conditions: ['browser']` for client targets) to guarantee hermetic AST virtualization.

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

Components and shared libraries NEVER import runtime-specific host modules (`node

Components and shared libraries NEVER import runtime-specific host modules (`node:fs`, `node:path`, `cloudflare:workers`) without runtime branch resolution guarded by environment module boundaries.

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 Module Boundary & AST Virtualization critical for AI coding assistants?

Enforces strict hermetic AST virtualization and module isolation across concurrent Browser, Edge Worker (WinterCG), and Node.js SSR runtime execution targets via the Vite 6 Environment API. Eliminates architectural leaks caused by legacy binary SSR assumptions and prevents cross-contamination of runtime-specific module graphs. 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 (Leaking Node.js Built-ins or Global Module Graph State into Edge and Client Runtimes via Legacy Binary SSR Assumptions) 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