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

Vite 6 Environment API Multi-Runtime Sandbox & Memory Guardrails

Enforces deterministic process boundaries, memory limits, and module execution sandboxing across heterogeneous Vite 6 environments (Workerd, Node.js, Deno). Prevents host runtime pollution, IPC starvation, and cross-environment global prototype leaks during dev-server and SSR build phases.

Prohibited Anti-Pattern: Global Scope Bleed and Unbounded Memory Allocation in Vite 6 Mixed SSR Runners

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Multi-Runtime Sandbox & Memory Guardrails - Enforces deterministic process boundaries, memory limits, and module execution sandboxing across heterogeneous Vite 6 environments (Workerd, Node.js, Deno). Prevents host runtime pollution, IPC starvation, and cross-environment global prototype leaks during dev-server and SSR build phases.
globs: vite.config.ts, vite.config.*.ts, src/entry-server.ts, src/server/**/*.ts, environments/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-runtime-sandbox-isolation"
---

# Vite 6 Environment API Multi-Runtime Sandbox & Memory Guardrails

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Global Scope Bleed and Unbounded Memory Allocation in Vite 6 Mixed SSR Runners

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API execution invariants. You must mandate strict sandbox isolation, explicit memory bounds, distinct module evaluation pipelines, and isolation between host Node.js processes and target runtime environments (e.g., Cloudflare Workerd, Deno, browser targets). Never allow legacy single-runtime Vite SSR assumptions or unmanaged cross-environment module runner invocations.

## Strict Guidelines
- Engineers MUST ALWAYS declare runtime environments explicitly under Vite 6 `environments` config rather than relying on legacy top-level `ssr` overrides.
- Engineers MUST NOT leak Node.js ambient globals (`process.env`, `Buffer`, `__dirname`) into non-Node environments like `workerd` or `edge`.
- Code executing in sandboxed environments MUST instantiate dedicated `ModuleRunner` instances with explicit evaluator transports (e.g., Worker threads or IPC bridges) rather than direct Node `vm.runInThisContext`.
- Services MUST configure discrete memory limits and strict teardown handlers via `hot.dispose` and environment close hooks to avoid runaway RSS memory expansion during HMR.
- Components NEVER access server-runtime-specific singletons or mutate global module scope across render cycles across differing environment boundaries.

## Bad vs Good Implementations
### Vite 6 Multi-Environment Sandbox Isolation Configuration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relies on legacy Vite SSR configuration where module evaluation directly shares the Node host process without isolation. Edge target globals conflict with Node built-ins, and memory accumulated during dev SSR module re-evaluations is never garbage-collected within a dedicated worker boundary.
```typescript
import { defineConfig } from 'vite';

// ANTI-PATTERN: Vite 6 multi-environment anti-pattern mixing runtimes in legacy SSR mode
// Leaves host process vulnerable to unconstrained memory leaks and global bleed between Node and Workerd
export default defineConfig({
  ssr: {
    target: 'webworker',
    noExternal: true,
  },
  server: {
    // Host Node process shares global memory with SSR evaluation context
    // Missing environment runner boundary; Node globals leak to target runtime
  }
});
```

#### Production Standard (Correct)
> **Standard**: Explicitly decouples Node and Edge runtimes using the Vite 6 Environment API. Configures segregated resolution conditions, enforces strict worker-thread memory quotas (512MB for Node SSR, 128MB for Workerd), and isolates the evaluation transport to eliminate global namespace pollution.
```typescript
import { defineConfig, DevEnvironment } from 'vite';
import { createWorkerdHandler } from 'workerd-vite-adapter';

// PRODUCTION INVARIANT: Vite 6 Environment API with isolated runner and strict process limits
export default defineConfig({
  environments: {
    ssr: {
      build: {
        outDir: 'dist/server',
      },
      resolve: {
        conditions: ['node', 'import'],
      },
      dev: {
        createEnvironment(name, config) {
          // Constrain worker thread heap to 512MB to prevent OOM cascade
          return new DevEnvironment(name, config, {
            runner: {
              transport: 'worker_threads',
              resourceLimits: { maxOldGenerationSizeMb: 512 },
            },
          });
        },
      },
    },
    edge: {
      resolve: {
        noExternal: true,
        conditions: ['workerd', 'worker'],
      },
      dev: {
        createEnvironment(name, config) {
          // Isolated workerd runtime context prevents Node global leakage
          return createWorkerdHandler(name, config, {
            memoryLimitMb: 128,
            isolatedGlobalScope: true,
          });
        },
      },
    },
  },
});
```

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 Multi-Runtime Sandbox & Memory Guardrails

Vite 6 Environment API Multi-Runtime Sandbox & Memory Guardrails defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic process boundaries, memory limits, and module execution sandboxing across heterogeneous Vite 6 environments (Workerd, Node.js, Deno). Prevents host runtime pollution, IPC starvation, and cross-environment global prototype leaks during dev-server and SSR build phases. 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: Global Scope Bleed and Unbounded Memory Allocation in Vite 6 Mixed SSR Runners 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 DriftGlobal Scope Bleed and Unbounded Memory Allocation in Vite 6 Mixed SSR RunnersCritical
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 runtime environments explicitly under Vite 6 `environments` config rather than relying on legacy top-level `ssr` overrides.

Engineers MUST ALWAYS declare runtime environments explicitly under Vite 6 `environments` config rather than relying on legacy top-level `ssr` overrides.

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 leak Node.js ambient globals (`process.env`, `Buffer`, `__dirname`) into non-Node environments like `workerd` or `edge`.

Engineers MUST NOT leak Node.js ambient globals (`process.env`, `Buffer`, `__dirname`) into non-Node environments like `workerd` or `edge`.

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 executing in sandboxed environments MUST instantiate dedicated `ModuleRunner` instances with explicit evaluator transports (e.g., Worker threads or IPC bridges) rather than direct Node `vm.runInThisContext`.

Code executing in sandboxed environments MUST instantiate dedicated `ModuleRunner` instances with explicit evaluator transports (e.g., Worker threads or IPC bridges) rather than direct Node `vm.runInThisContext`.

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

Services MUST configure discrete memory limits and strict teardown handlers via `hot.dispose` and environment close hooks to avoid runaway RSS memory expansion during HMR.

Services MUST configure discrete memory limits and strict teardown handlers via `hot.dispose` and environment close hooks to avoid runaway RSS memory expansion during HMR.

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 NEVER access server-runtime-specific singletons or mutate global module scope across render cycles across differing environment boundaries.

Components NEVER access server-runtime-specific singletons or mutate global module scope across render cycles across differing environment 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 Multi-Runtime Sandbox & Memory Guardrails critical for AI coding assistants?

Enforces deterministic process boundaries, memory limits, and module execution sandboxing across heterogeneous Vite 6 environments (Workerd, Node.js, Deno). Prevents host runtime pollution, IPC starvation, and cross-environment global prototype leaks during dev-server and SSR build phases. 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 (Global Scope Bleed and Unbounded Memory Allocation in Vite 6 Mixed SSR Runners) 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