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

Vite 6 Environment API Module-Graph SSR Boundary & Runtime Isolation

Enforces strict boundary separation between client, Node.js, and edge module graphs using the Vite 6 Environment API. Eliminates cross-runtime singleton leaks, improper HMR propagation, and shared state bleed between SSR execution contexts during local development and build pipelines.

Prohibited Anti-Pattern: Accessing Legacy Shared ModuleGraph and ssrLoadModule Leading to Cross-Runtime State Contamination

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Vite 6 Environment API Module-Graph SSR Boundary & Runtime Isolation - Enforces strict boundary separation between client, Node.js, and edge module graphs using the Vite 6 Environment API. Eliminates cross-runtime singleton leaks, improper HMR propagation, and shared state bleed between SSR execution contexts during local development and build pipelines.
globs: vite.config.ts, vite.config.mts, server.ts, src/entry-server.{ts,tsx}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/vite6-environment-api-ssr-isolation-guardrail"
---

# Vite 6 Environment API Module-Graph SSR Boundary & Runtime Isolation

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Accessing Legacy Shared ModuleGraph and ssrLoadModule Leading to Cross-Runtime State Contamination

## System Constraints
You are a Principal Software Architect enforcing Vite 6 Environment API Module-Graph SSR Isolation. You must mandate strict separation between client, Node, and edge runtime environments. Deprecate and prohibit all legacy Vite 5 patterns such as direct access to server.moduleGraph, server.ssrLoadModule, and server.ssrFixStacktrace. Require explicit environment definitions, runner-isolated imports via server.environments[envName].runner.import(), and environment-isolated HMR channels to eliminate cross-runtime singleton and module-cache pollution.

## Strict Guidelines
- Engineers MUST configure distinct environments in `vite.config.ts` using the top-level `environments` config map (e.g., `client`, `ssr`, `edge`, `workerd`).
- Engineers MUST NOT access `server.moduleGraph` directly; all module lookups and invalidations MUST target `server.environments[envName].moduleGraph`.
- Engineers MUST NOT invoke `server.ssrLoadModule()` or `server.ssrFixStacktrace()`; invoke `server.environments.ssr.runner.import()` or `createViteRuntime` on the designated environment runner.
- Engineers MUST NOT share in-memory singletons (e.g., database clients, auth caches, store instances) across runtime environment boundaries without scoped lifecycle wrappers.
- Code SHOULD route custom Hot Module Replacement (HMR) messages through the targeted environment channel (`server.environments[envName].hot.send`) rather than broadcasting indiscriminately to all clients.
- Services MUST ensure that plugins hooked into `buildStart` or `resolveId` evaluate `this.environment.name` to avoid applying client-specific transforms to the SSR or edge module graphs.

## Bad vs Good Implementations
### Migrate from Vite 5 Global SSR Dev Server to Vite 6 Environment API Runner

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using `server.ssrLoadModule` and `server.ssrFixStacktrace` relies on the deprecated Vite 5 legacy SSR pipeline. This conflates client and SSR transformation caches in a single shared module graph, causing singleton leaks, incorrect HMR invalidation, and potential cross-runtime memory leaks.
```typescript
import { createServer } from 'vite';
import type { Request, Response } from 'express';

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

// ANTI-PATTERN: Vite 5 legacy module loading and shared module graph pollution
export async function handleRequest(req: Request, res: Response): Promise<void> {
  try {
    // Pollutes global module graph, shares singletons with client transforms
    const { render } = await server.ssrLoadModule('/src/entry-server.ts');
    const html = await render(req.originalUrl);
    res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
  } catch (e: unknown) {
    if (e instanceof Error) {
      server.ssrFixStacktrace(e);
    }
    res.status(500).end(String(e));
  }
}
```

#### Production Standard (Correct)
> **Standard**: Using Vite 6's `environments.ssr` config and `RunnableDevEnvironment.runner.import()` ensures that the server module graph is completely isolated from the client module graph. HMR boundaries and error stack processing are strictly scoped to the SSR runtime environment.
```typescript
import { createServer, type RunnableDevEnvironment } from 'vite';
import type { Request, Response } from 'express';

const server = await createServer({
  server: { middlewareMode: true },
  appType: 'custom',
  environments: {
    ssr: {
      build: { ssr: true },
      resolve: { conditions: ['node'] },
    },
  },
});

// PRODUCTION INVARIANT: Vite 6 isolated Environment API runner and scoped module graph
export async function handleRequest(req: Request, res: Response): Promise<void> {
  const ssrEnvironment = server.environments.ssr as RunnableDevEnvironment;
  if (!ssrEnvironment || !ssrEnvironment.runner) {
    throw new Error('SSR environment runner is not initialized');
  }

  try {
    // Module execution is strictly isolated to the SSR environment
    const { render } = await ssrEnvironment.runner.import('/src/entry-server.ts');
    const html = await render(req.originalUrl);
    res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
  } catch (e: unknown) {
    if (e instanceof Error) {
      // Stack traces are fixed per environment
      ssrEnvironment.runner.processError(e);
    }
    res.status(500).end(String(e));
  }
}
```

### Environment-Aware Plugin Boundary Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The plugin does not inspect `this.environment.name`. As a result, sensitive Node.js process environment variables get bundled into the client environment graph when a client file imports `virtual:config`.
```typescript
import type { Plugin } from 'vite';

export function brokenVirtualModulePlugin(): Plugin {
  return {
    name: 'virtual-config',
    resolveId(id) {
      if (id === 'virtual:config') return id;
    },
    load(id) {
      // ANTI-PATTERN: Blindly returns Node process globals even when loaded by client environment
      if (id === 'virtual:config') {
        return `export const config = ${JSON.stringify(process.env)};`;
      }
    },
  };
}
```

#### Production Standard (Correct)
> **Standard**: Inspecting `this.environment.name` in plugin hooks prevents leaking server configurations or Node-specific implementations into the client module graph during dev, HMR, and build phases.
```typescript
import type { Plugin } from 'vite';

export function safeVirtualModulePlugin(): Plugin {
  return {
    name: 'virtual-config',
    resolveId(id) {
      if (id === 'virtual:config') return id;
    },
    load(id) {
      if (id !== 'virtual:config') return null;

      // PRODUCTION INVARIANT: Branch transformations based on current environment context
      if (this.environment.name === 'client') {
        return 'export const config = { isServer: false };';
      }

      return `export const config = { isServer: true, nodeEnv: ${JSON.stringify(process.env.NODE_ENV)} };`;
    },
  };
}
```

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 Module-Graph SSR Boundary & Runtime Isolation

Vite 6 Environment API Module-Graph SSR Boundary & Runtime Isolation defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary separation between client, Node.js, and edge module graphs using the Vite 6 Environment API. Eliminates cross-runtime singleton leaks, improper HMR propagation, and shared state bleed between SSR execution contexts during local development and build pipelines. 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: Accessing Legacy Shared ModuleGraph and ssrLoadModule Leading to Cross-Runtime State Contamination 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 DriftAccessing Legacy Shared ModuleGraph and ssrLoadModule Leading to Cross-Runtime State ContaminationCritical
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 configure distinct environments in `vite.config.ts` using the top-level `environments` config map (e.g., `client`, `ssr`, `edge`, `workerd`).

Engineers MUST configure distinct environments in `vite.config.ts` using the top-level `environments` config map (e.g., `client`, `ssr`, `edge`, `workerd`).

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 access `server.moduleGraph` directly

Engineers MUST NOT access `server.moduleGraph` directly; all module lookups and invalidations MUST target `server.environments[envName].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.
3

Engineers MUST NOT invoke `server.ssrLoadModule()` or `server.ssrFixStacktrace()`

Engineers MUST NOT invoke `server.ssrLoadModule()` or `server.ssrFixStacktrace()`; invoke `server.environments.ssr.runner.import()` or `createViteRuntime` on the designated environment runner.

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

Engineers MUST NOT share in-memory singletons (e.g., database clients, auth caches, store instances) across runtime environment boundaries without scoped lifecycle wrappers.

Engineers MUST NOT share in-memory singletons (e.g., database clients, auth caches, store instances) across runtime environment boundaries without scoped lifecycle wrappers.

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

Code SHOULD route custom Hot Module Replacement (HMR) messages through the targeted environment channel (`server.environments[envName].hot.send`) rather than broadcasting indiscriminately to all clients.

Code SHOULD route custom Hot Module Replacement (HMR) messages through the targeted environment channel (`server.environments[envName].hot.send`) rather than broadcasting indiscriminately to all clients.

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

Services MUST ensure that plugins hooked into `buildStart` or `resolveId` evaluate `this.environment.name` to avoid applying client-specific transforms to the SSR or edge module graphs.

Services MUST ensure that plugins hooked into `buildStart` or `resolveId` evaluate `this.environment.name` to avoid applying client-specific transforms to the SSR or edge module graphs.

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 Module-Graph SSR Boundary & Runtime Isolation critical for AI coding assistants?

Enforces strict boundary separation between client, Node.js, and edge module graphs using the Vite 6 Environment API. Eliminates cross-runtime singleton leaks, improper HMR propagation, and shared state bleed between SSR execution contexts during local development and build pipelines. 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 (Accessing Legacy Shared ModuleGraph and ssrLoadModule Leading to Cross-Runtime State Contamination) 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