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

Strict Module & Environment Isolation via Vite 6 Environment API

Enforces complete module graph and execution environment segregation across client, edge (workerd), and Node.js runtimes using the Vite 6 Environment API. Prevents cross-runtime module leakage, unconditioned Node.js built-ins in edge/client bundles, and monolithic plugin side-effects across heterogeneous runtime boundaries.

Prohibited Anti-Pattern: Cross-Pollinating Module Graphs and Leaking Server Runables into Heterogeneous Vite Environments

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Strict Module & Environment Isolation via Vite 6 Environment API - Enforces complete module graph and execution environment segregation across client, edge (workerd), and Node.js runtimes using the Vite 6 Environment API. Prevents cross-runtime module leakage, unconditioned Node.js built-ins in edge/client bundles, and monolithic plugin side-effects across heterogeneous runtime boundaries.
globs: vite.config.ts, vite.config.*.ts, src/entry.server.ts, src/entry.client.ts, src/entry.edge.ts, src/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-runtime-decoupling-vite-6-environme-769"
---

# Strict Module & Environment Isolation via Vite 6 Environment API

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Pollinating Module Graphs and Leaking Server Runables into Heterogeneous Vite Environments

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API standards. Vite 6 deprecates monolithic `ssrLoadModule` in favor of explicit per-environment module graphs (client, ssr, edge). You must strictly prevent cross-environment pollution, ensure environment-specific resolve and externalization conditions, and enforce decoupled plugin hooks targeting `this.environment`.

## Strict Guidelines
- Engineers MUST ALWAYS configure distinct environments using `environments.<name>` in Vite 6, setting explicitly scoped `resolve.conditions` and `consumer` properties (e.g., 'client', 'server').
- Engineers MUST NEVER invoke deprecated monolithic runtime methods like `server.ssrLoadModule()` or `server.ssrFixStacktrace()`; use `server.environments[name].runner.import()` instead.
- Vite plugins MUST inspect `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) when altering resolutions or injecting code intended for only one target runtime.
- Code targeting edge environments (e.g., Cloudflare Workers / workerd) MUST NOT import Node.js native built-ins (such as 'node:fs' or 'node:child_process') unless polyfilled or supported under explicit edge runtime flags.
- Engineers MUST configure explicit `external` and `noExternal` bundling rules uniquely per environment within `environments.<name>.resolve.external` to avoid shipping server packages to the client graph.
- HMR boundaries MUST be isolated per environment; client module changes MUST NOT invalidate or crash the headless edge or Node server runner instances.

## Bad vs Good Implementations
### Vite 6 Decoupled Environment Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Configuring SSR via monolithic top-level `ssr` settings forces edge and Node runtimes to share condition paths, risking cross-contamination of globals, leaking Node APIs into client graphs, and preventing multi-environment orchestration.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Monolithic SSR and Client shared config in Vite 5 style
export default defineConfig({
  build: {
    ssr: true,
  },
  ssr: {
    noExternal: ['lodash-es'],
    target: 'node',
  },
  resolve: {
    // Shared conditions leak Node-specific logic into client or edge
    conditions: ['node', 'import', 'module'],
  },
});
```

#### Production Standard (Correct)
> **Standard**: Defines isolated environment boundaries with explicit export conditions and externalization schemes for browser, Node.js, and Cloudflare workerd runtimes.
```typescript
import { defineConfig } from 'vite';
import { createRunnableDevEnvironment } from 'vite';

// PRODUCTION INVARIANT: Vite 6 Environment API with isolated runtime topologies
export default defineConfig({
  environments: {
    client: {
      build: {
        outDir: 'dist/client',
      },
      resolve: {
        conditions: ['browser', 'import', 'module'],
      },
    },
    ssr: {
      build: {
        outDir: 'dist/server',
      },
      resolve: {
        conditions: ['node', 'import', 'module'],
        external: ['node:*'],
      },
    },
    edge: {
      build: {
        outDir: 'dist/edge',
      },
      resolve: {
        conditions: ['workerd', 'worker', 'browser'],
        noExternal: true,
      },
    },
  },
});
```

### Runtime Runner Execution and Environment-Aware Plugin Hook

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses the deprecated Vite 5 `server.ssrLoadModule()` API and applies runtime transforms indiscriminately across all environments, breaking the client and edge module graphs.
```typescript
import type { Plugin, ViteDevServer } from 'vite';

export function brokenServerRunnerPlugin(): Plugin {
  return {
    name: 'broken-server-runner',
    configureServer(server: ViteDevServer) {
      server.middlewares.use(async (req, res, next) => {
        // ANTI-PATTERN: Using deprecated ssrLoadModule from monolithic server
        const entry = await server.ssrLoadModule('/src/entry.server.ts');
        entry.render(req, res);
      });
    },
    transform(code, id) {
      // ANTI-PATTERN: Blindly injecting Node globals into all environments
      return `import process from 'node:process';\n${code}`;
    }
  };
}
```

#### Production Standard (Correct)
> **Standard**: Safely isolates server evaluation via `server.environments[name].runner.import` and gates code transformations strictly on `this.environment.name`.
```typescript
import type { Plugin, ViteDevServer } from 'vite';

export function decoupledEnvironmentPlugin(): Plugin {
  return {
    name: 'decoupled-environment-plugin',
    configureServer(server: ViteDevServer) {
      server.middlewares.use(async (req, res, next) => {
        const ssrEnv = server.environments.ssr;
        if (!ssrEnv) {
          return next(new Error('SSR Environment is not initialized'));
        }
        // PRODUCTION INVARIANT: Use Environment Runner to evaluate modules per environment
        const entry = await ssrEnv.runner.import('/src/entry.server.ts');
        entry.render(req, res);
      });
    },
    transform(code, id) {
      // PRODUCTION INVARIANT: Query execution context per environment
      if (this.environment.name === 'ssr') {
        return {
          code: `import process from 'node:process';\n${code}`,
          map: null,
        };
      }
      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: Strict Module & Environment Isolation via Vite 6 Environment API

Strict Module & Environment Isolation via Vite 6 Environment API defines an industrial-grade behavioral standard for frontend engineering. Enforces complete module graph and execution environment segregation across client, edge (workerd), and Node.js runtimes using the Vite 6 Environment API. Prevents cross-runtime module leakage, unconditioned Node.js built-ins in edge/client bundles, and monolithic plugin side-effects across heterogeneous runtime boundaries. 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-Pollinating Module Graphs and Leaking Server Runables into Heterogeneous Vite Environments 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-Pollinating Module Graphs and Leaking Server Runables into Heterogeneous Vite EnvironmentsCritical
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 distinct environments using `environments.<name>` in Vite 6, setting explicitly scoped `resolve.conditions` and `consumer` properties (e.g., 'client', 'server').

Engineers MUST ALWAYS configure distinct environments using `environments.<name>` in Vite 6, setting explicitly scoped `resolve.conditions` and `consumer` properties (e.g., 'client', 'server').

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 invoke deprecated monolithic runtime methods like `server.ssrLoadModule()` or `server.ssrFixStacktrace()`

Engineers MUST NEVER invoke deprecated monolithic runtime methods like `server.ssrLoadModule()` or `server.ssrFixStacktrace()`; use `server.environments[name].runner.import()` instead.

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 plugins MUST inspect `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) when altering resolutions or injecting code intended for only one target runtime.

Vite plugins MUST inspect `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) when altering resolutions or injecting code intended for only one target 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.
4

Code targeting edge environments (e.g., Cloudflare Workers / workerd) MUST NOT import Node.js native built-ins (such as 'node

Code targeting edge environments (e.g., Cloudflare Workers / workerd) MUST NOT import Node.js native built-ins (such as 'node:fs' or 'node:child_process') unless polyfilled or supported under explicit edge runtime 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.
5

Engineers MUST configure explicit `external` and `noExternal` bundling rules uniquely per environment within `environments.<name>.resolve.external` to avoid shipping server packages to the client graph.

Engineers MUST configure explicit `external` and `noExternal` bundling rules uniquely per environment within `environments.<name>.resolve.external` to avoid shipping server packages to the client 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

HMR boundaries MUST be isolated per environment

HMR boundaries MUST be isolated per environment; client module changes MUST NOT invalidate or crash the headless edge or Node server runner instances.

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 Strict Module & Environment Isolation via Vite 6 Environment API critical for AI coding assistants?

Enforces complete module graph and execution environment segregation across client, edge (workerd), and Node.js runtimes using the Vite 6 Environment API. Prevents cross-runtime module leakage, unconditioned Node.js built-ins in edge/client bundles, and monolithic plugin side-effects across heterogeneous runtime boundaries. 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-Pollinating Module Graphs and Leaking Server Runables into Heterogeneous Vite Environments) 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

Strict