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-sandbox-invariant

Vite 6 Environment API Cross-Runtime Sandbox Invariant

Enforces strict execution boundaries across heterogeneous runtimes (Browser, Node.js SSR, and Edge/Workerd) managed by the Vite 6 Environment API. Prohibits ambient global state pollution, cross-runtime module graph leakage, and legacy non-scoped SSR hooks during build and HMR cycles. Guarantees deterministic module evaluation across concurrently active DevEnvironment instances.

Prohibited Anti-Pattern: Ambient Global Mutation and Cross-Environment Module Graph Coupling in Multi-Runtime Vite Applications

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Cross-Runtime Sandbox Invariant - Enforces strict execution boundaries across heterogeneous runtimes (Browser, Node.js SSR, and Edge/Workerd) managed by the Vite 6 Environment API. Prohibits ambient global state pollution, cross-runtime module graph leakage, and legacy non-scoped SSR hooks during build and HMR cycles. Guarantees deterministic module evaluation across concurrently active DevEnvironment instances.
globs: vite.config.{ts,js,mjs}, src/**/*.{ts,tsx,js,jsx}, server/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-cross-runtime-sandbox-invariant"
---

# Vite 6 Environment API Cross-Runtime Sandbox Invariant

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Ambient Global Mutation and Cross-Environment Module Graph Coupling in Multi-Runtime Vite Applications

## System Constraints
You are a Principal Engineer enforcing Vite 6 Environment API Cross-Runtime Sandbox Invariants. Vite 6 coordinates multiple environments (e.g., client, ssr, edge/workerd) inside a single dev server process. You must eliminate cross-environment global pollution, ban deprecated pre-Vite-6 SSR APIs (such as server.ssrLoadModule and server.moduleGraph), mandate environment-scoped plugin hooks (this.environment), and ensure absolute isolation between Node.js and Edge/Worker runtimes.

## Strict Guidelines
- Engineers MUST ALWAYS access the module graph and transformation pipeline through 'this.environment' inside Vite plugin hooks (e.g., 'this.environment.moduleGraph') rather than root 'server.moduleGraph'.
- Engineers MUST NEVER invoke deprecated Vite 5 SSR APIs including 'server.ssrLoadModule', 'server.ssrFixStacktrace', or 'server.ssrTransform'; the Vite 6 Environment API equivalents ('environment.runner.import' or 'environment.transformRequest') MUST be used instead.
- Code evaluated across multi-runtime boundaries MUST NEVER mutate 'globalThis', 'window', or Node-specific globals ('process.env') directly without runtime capability guardrails and environment-scoped shims.
- Plugins targeting heterogeneous environments MUST implement the 'applyToEnvironment(environment)' hook or verify 'this.environment.name' to prevent runtime-incompatible AST transforms from executing on unsupported targets.
- Services running in isolated Edge runtimes (such as Workerd via Miniflare) MUST be instantiated with dedicated 'RunnableDevEnvironment' or 'DevEnvironment' configs and communicated with strictly via standard Request/Response or environment transport channels.
- Components NEVER import Node.js built-ins ('fs', 'path', 'node:crypto') into modules resolved within non-Node runtime environments (e.g., edge, workerd, or client) without an explicit conditional environment export or virtual module shim.

## Bad vs Good Implementations
### Cross-Runtime Environment Hook & Runner Migration in Vite 6

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Accessing devServer.moduleGraph collapses all distinct runtime graphs (client, ssr, edge) into a single polluted namespace. Mutating globalThis directly infects concurrent runs across different environments. Using devServer.ssrLoadModule invokes deprecated Vite 5 code paths that bypass Vite 6 Environment sandboxing.
```typescript
import { Plugin, ViteDevServer } from 'vite';

export function legacySsrPlugin(): Plugin {
  let devServer: ViteDevServer;
  return {
    name: 'legacy-ssr-plugin',
    configureServer(server) {
      devServer = server;
    },
    async transform(code, id) {
      // VIOLATION: Using server.moduleGraph leaks modules across client & edge environments
      const mod = devServer.moduleGraph.getModuleById(id);
      if (mod && mod.ssrTransformResult) {
        // VIOLATION: Global pollution affecting all runtimes
        (globalThis as Record<string, unknown>).__RUNTIME_ID = 'node-ssr';
      }
      // VIOLATION: Calling deprecated Vite 5 ssrLoadModule from root server
      if (id.endsWith('entry.server.ts')) {
        await devServer.ssrLoadModule(id);
      }
      return code;
    }
  };
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to Vite 6 Environment API standards by using 'applyToEnvironment' to scope execution, retrieving the environment-scoped module graph via 'this.environment.moduleGraph', and evaluating entry modules within the target runtime sandbox via 'environment.runner.import'.
```typescript
import { Plugin, EnvironmentModuleNode } from 'vite';

export function isolatedEnvironmentPlugin(): Plugin {
  return {
    name: 'isolated-environment-plugin',
    // Vite 6: Conditionally apply plugin only to targeted environments
    applyToEnvironment(environment) {
      return environment.name === 'ssr' || environment.name === 'edge';
    },
    async transform(code, id) {
      // Vite 6: Invariant enforced via this.environment context
      const currentEnv = this.environment;
      const mod: EnvironmentModuleNode | undefined = currentEnv.moduleGraph.getModuleById(id);
      
      if (!mod) {
        return null;
      }

      // Safe execution using Environment Runner instead of root server.ssrLoadModule
      if (id.endsWith('entry.server.ts') && 'runner' in currentEnv) {
        const runnableEnv = currentEnv as import('vite').RunnableDevEnvironment;
        await runnableEnv.runner.import(id);
      }

      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: Vite 6 Environment API Cross-Runtime Sandbox Invariant

Vite 6 Environment API Cross-Runtime Sandbox Invariant defines an industrial-grade behavioral standard for frontend engineering. Enforces strict execution boundaries across heterogeneous runtimes (Browser, Node.js SSR, and Edge/Workerd) managed by the Vite 6 Environment API. Prohibits ambient global state pollution, cross-runtime module graph leakage, and legacy non-scoped SSR hooks during build and HMR cycles. Guarantees deterministic module evaluation across concurrently active DevEnvironment instances. 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: Ambient Global Mutation and Cross-Environment Module Graph Coupling in Multi-Runtime Vite Applications 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 DriftAmbient Global Mutation and Cross-Environment Module Graph Coupling in Multi-Runtime Vite ApplicationsCritical
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 access the module graph and transformation pipeline through 'this.environment' inside Vite plugin hooks (e.g., 'this.environment.moduleGraph') rather than root 'server.moduleGraph'.

Engineers MUST ALWAYS access the module graph and transformation pipeline through 'this.environment' inside Vite plugin hooks (e.g., 'this.environment.moduleGraph') rather than root 'server.moduleGraph'.

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 Vite 5 SSR APIs including 'server.ssrLoadModule', 'server.ssrFixStacktrace', or 'server.ssrTransform'

Engineers MUST NEVER invoke deprecated Vite 5 SSR APIs including 'server.ssrLoadModule', 'server.ssrFixStacktrace', or 'server.ssrTransform'; the Vite 6 Environment API equivalents ('environment.runner.import' or 'environment.transformRequest') MUST be used 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

Code evaluated across multi-runtime boundaries MUST NEVER mutate 'globalThis', 'window', or Node-specific globals ('process.env') directly without runtime capability guardrails and environment-scoped shims.

Code evaluated across multi-runtime boundaries MUST NEVER mutate 'globalThis', 'window', or Node-specific globals ('process.env') directly without runtime capability guardrails and environment-scoped 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

Plugins targeting heterogeneous environments MUST implement the 'applyToEnvironment(environment)' hook or verify 'this.environment.name' to prevent runtime-incompatible AST transforms from executing on unsupported targets.

Plugins targeting heterogeneous environments MUST implement the 'applyToEnvironment(environment)' hook or verify 'this.environment.name' to prevent runtime-incompatible AST transforms from executing on unsupported 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

Services running in isolated Edge runtimes (such as Workerd via Miniflare) MUST be instantiated with dedicated 'RunnableDevEnvironment' or 'DevEnvironment' configs and communicated with strictly via standard Request/Response or environment transport channels.

Services running in isolated Edge runtimes (such as Workerd via Miniflare) MUST be instantiated with dedicated 'RunnableDevEnvironment' or 'DevEnvironment' configs and communicated with strictly via standard Request/Response or environment transport channels.

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 NEVER import Node.js built-ins ('fs', 'path', 'node

Components NEVER import Node.js built-ins ('fs', 'path', 'node:crypto') into modules resolved within non-Node runtime environments (e.g., edge, workerd, or client) without an explicit conditional environment export or virtual module shim.

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 Sandbox Invariant critical for AI coding assistants?

Enforces strict execution boundaries across heterogeneous runtimes (Browser, Node.js SSR, and Edge/Workerd) managed by the Vite 6 Environment API. Prohibits ambient global state pollution, cross-runtime module graph leakage, and legacy non-scoped SSR hooks during build and HMR cycles. Guarantees deterministic module evaluation across concurrently active DevEnvironment instances. 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 (Ambient Global Mutation and Cross-Environment Module Graph Coupling in Multi-Runtime Vite Applications) 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