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

Vite 6 Environment API Heterogeneous SSR Runtime Isolation

Enforces strict runtime and module-graph boundary isolation across heterogeneous SSR execution targets (e.g., Workerd, Node.js, Deno) cohabiting a single Vite 6 dev server. Mandates dedicated DevEnvironment instances, eliminates legacy ssrLoadModule usage, and prevents cross-environment global singleton leakage.

Prohibited Anti-Pattern: Cross-Runtime Module Graph Contamination & Deprecated ssrLoadModule Invocations in Heterogeneous SSR Dev Servers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Heterogeneous SSR Runtime Isolation - Enforces strict runtime and module-graph boundary isolation across heterogeneous SSR execution targets (e.g., Workerd, Node.js, Deno) cohabiting a single Vite 6 dev server. Mandates dedicated DevEnvironment instances, eliminates legacy ssrLoadModule usage, and prevents cross-environment global singleton leakage.
globs: vite.config.{ts,js,mjs}, server/**/*.{ts,tsx,js}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-ssr-environment-isolation-barrier"
---

# Vite 6 Environment API Heterogeneous SSR Runtime Isolation

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Runtime Module Graph Contamination & Deprecated ssrLoadModule Invocations in Heterogeneous SSR Dev Servers

## System Constraints
You are a Principal Software Architect enforcing deterministic SSR isolation using the Vite 6 Environment API. You must eradicate legacy Vite 5 SSR patterns (e.g., server.ssrLoadModule, server.ssrFixStacktrace) and prevent cross-environment pollution where Workerd, Node, or Deno share a single dev server instance. Enforce strict isolation at the DevEnvironment runner, transform pipeline, and module graph levels.

## Strict Guidelines
- Engineers MUST ALWAYS use Vite 6 `DevEnvironment` runners (`server.environments[name].runner.import()`) instead of the deprecated `server.ssrLoadModule()` when targeting heterogeneous execution environments.
- Engineers MUST configure discrete environment targets under `environments` in `vite.config.ts` (e.g., `client`, `ssr`, `edge`) with runtime-specific `resolve.conditions`, `resolve.noExternal`, and execution transports.
- Vite plugins MUST inspect `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) before applying runtime-specific transformations, polyfills, or native bindings.
- Code executed within edge/Workerd environments MUST NOT reference Node.js runtime singletons (`process.cwd()`, Node `Buffer`, `AsyncLocalStorage` without `node:` imports) unless explicitly provided via Workerd compatibility flags.
- Server entrypoints MUST NOT share in-memory cache, module-level mutable variables, or global polyfill mutators across different `DevEnvironment` boundaries.
- HMR invalidation logic MUST target the specific `server.environments[name].moduleGraph` to prevent cross-runtime transform cascading and cache thrashing.

## Bad vs Good Implementations
### Heterogeneous Dev Server Orchestration: Legacy ssrLoadModule vs Vite 6 Environment API Runner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly calling `server.ssrLoadModule` forces the bundle through Node's VM context, ignoring Vite 6 Environment configurations. It contaminates edge runtime logic (like Cloudflare Workers/Workerd) with Node global namespaces, corrupts the module graph, and circumvents environment-specific runtime runners.
```typescript
import { createServer } from 'vite';
import type { IncomingMessage, ServerResponse } from 'node:http';

const server = await createServer({
  server: { middlewareMode: true },
  appType: 'custom',
});

// ANTI-PATTERN: Vite 5 legacy SSR invocation leaks Node runtime into edge code
// and forces all SSR code through a single default Node.js module graph.
export async function handleRequest(req: IncomingMessage, res: ServerResponse) {
  try {
    const url = req.url!;
    const template = await server.transformIndexHtml(url, '');
    // ssrLoadModule uses Node VM execution directly; crashes or contaminates Workerd/Deno contexts
    const { render } = await server.ssrLoadModule('/src/entry.server.ts');
    const appHtml = await render(url);
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(template.replace('<!--app-html-->', appHtml));
  } catch (e: any) {
    server.ssrFixStacktrace(e);
    res.statusCode = 500;
    res.end(e.stack);
  }
}
```

#### Production Standard (Correct)
> **Standard**: Adheres to the Vite 6 Environment API. Isolate the Workerd SSR runtime with its own resolve conditions and execute code via `workerdEnv.runner.import()`, preventing Node.js host context pollution.
```typescript
import { createServer } from 'vite';
import type { IncomingMessage, ServerResponse } from 'node:http';

const server = await createServer({
  server: { middlewareMode: true },
  appType: 'custom',
  environments: {
    client: {},
    // Discrete Workerd edge SSR environment declaration
    workerd: {
      resolve: {
        conditions: ['workerd', 'worker', 'browser'],
        noExternal: true,
      },
    },
  },
});

export async function handleRequest(req: IncomingMessage, res: ServerResponse) {
  try {
    const url = req.url!;
    const workerdEnv = server.environments.workerd;
    if (!workerdEnv) {
      throw new Error('Workerd dev environment not registered.');
    }

    // Vite 6 standard: Environment-isolated runner invocation
    const { render } = await workerdEnv.runner.import('/src/entry.workerd.ts');
    const appHtml = await render(url);

    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    res.end(appHtml);
  } catch (e: unknown) {
    // Use environment-specific stack trace sanitization
    server.environments.workerd.runner.processError(e as Error);
    res.statusCode = 500;
    res.end((e as Error).stack);
  }
}
```

### Environment-Aware Plugin Hook Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The transform hook executes unconditionally for all environments, illegally injecting Node.js built-ins into non-Node targets such as Workerd or browser client bundles.
```typescript
import type { Plugin } from 'vite';

export function leakyRuntimePlugin(): Plugin {
  return {
    name: 'leaky-runtime-plugin',
    transform(code, id) {
      // ANTI-PATTERN: Transforms code universally without checking target environment.
      // Injects Node-specific globals into client or edge (Workerd) environments.
      if (id.endsWith('.server.ts')) {
        return `import { AsyncLocalStorage } from 'node:async_hooks';
${code}`;
      }
      return code;
    },
  };
}
```

#### Production Standard (Correct)
> **Standard**: Validates `this.environment.name` inside plugin lifecycle hooks, ensuring that Node-specific APIs and transformations are strictly quarantined from Workerd, Deno, and client runtime builds.
```typescript
import type { Plugin } from 'vite';

export function isolatedRuntimePlugin(): Plugin {
  return {
    name: 'isolated-runtime-plugin',
    transform(code, id) {
      // Vite 6 standard: Guard transformation using this.environment
      if (this.environment.name !== 'ssr-node') {
        return null;
      }

      if (id.endsWith('.server.node.ts')) {
        return {
          code: `import { AsyncLocalStorage } from 'node:async_hooks';\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: Vite 6 Environment API Heterogeneous SSR Runtime Isolation

Vite 6 Environment API Heterogeneous SSR Runtime Isolation defines an industrial-grade behavioral standard for frontend engineering. Enforces strict runtime and module-graph boundary isolation across heterogeneous SSR execution targets (e.g., Workerd, Node.js, Deno) cohabiting a single Vite 6 dev server. Mandates dedicated DevEnvironment instances, eliminates legacy ssrLoadModule usage, and prevents cross-environment global singleton leakage. 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-Runtime Module Graph Contamination & Deprecated ssrLoadModule Invocations in Heterogeneous SSR Dev Servers 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-Runtime Module Graph Contamination & Deprecated ssrLoadModule Invocations in Heterogeneous SSR Dev ServersCritical
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 use Vite 6 `DevEnvironment` runners (`server.environments[name].runner.import()`) instead of the deprecated `server.ssrLoadModule()` when targeting heterogeneous execution environments.

Engineers MUST ALWAYS use Vite 6 `DevEnvironment` runners (`server.environments[name].runner.import()`) instead of the deprecated `server.ssrLoadModule()` when targeting heterogeneous execution 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.
2

Engineers MUST configure discrete environment targets under `environments` in `vite.config.ts` (e.g., `client`, `ssr`, `edge`) with runtime-specific `resolve.conditions`, `resolve.noExternal`, and execution transports.

Engineers MUST configure discrete environment targets under `environments` in `vite.config.ts` (e.g., `client`, `ssr`, `edge`) with runtime-specific `resolve.conditions`, `resolve.noExternal`, and execution transports.

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`) before applying runtime-specific transformations, polyfills, or native bindings.

Vite plugins MUST inspect `this.environment.name` inside lifecycle hooks (`resolveId`, `load`, `transform`) before applying runtime-specific transformations, polyfills, or native bindings.

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 executed within edge/Workerd environments MUST NOT reference Node.js runtime singletons (`process.cwd()`, Node `Buffer`, `AsyncLocalStorage` without `node

Code executed within edge/Workerd environments MUST NOT reference Node.js runtime singletons (`process.cwd()`, Node `Buffer`, `AsyncLocalStorage` without `node:` imports) unless explicitly provided via Workerd compatibility 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

Server entrypoints MUST NOT share in-memory cache, module-level mutable variables, or global polyfill mutators across different `DevEnvironment` boundaries.

Server entrypoints MUST NOT share in-memory cache, module-level mutable variables, or global polyfill mutators across different `DevEnvironment` 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.
6

HMR invalidation logic MUST target the specific `server.environments[name].moduleGraph` to prevent cross-runtime transform cascading and cache thrashing.

HMR invalidation logic MUST target the specific `server.environments[name].moduleGraph` to prevent cross-runtime transform cascading and cache thrashing.

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 Heterogeneous SSR Runtime Isolation critical for AI coding assistants?

Enforces strict runtime and module-graph boundary isolation across heterogeneous SSR execution targets (e.g., Workerd, Node.js, Deno) cohabiting a single Vite 6 dev server. Mandates dedicated DevEnvironment instances, eliminates legacy ssrLoadModule usage, and prevents cross-environment global singleton leakage. 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-Runtime Module Graph Contamination & Deprecated ssrLoadModule Invocations in Heterogeneous SSR Dev Servers) 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