This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: nuxt4-nitro-shared-ssr-state-isolation-production-standard

Nuxt 4 Nitro Server Engine Isolation & Shared Directory Hydration Guardrail

Enforces strict architectural boundaries across the Nuxt 4 directory layout (app/, server/, and shared/) to prevent cross-request SSR state pollution and runtime hydration mismatches. Mandates request-scoped context within Nitro event handlers and restricts the shared/ layer to stateless, isomorphic code.

Prohibited Anti-Pattern: Cross-Request State Leaks via Global Module Scope in Nitro Handlers and Isomorphic Boundary Violations in Nuxt 4 shared/

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Server Engine Isolation & Shared Directory Hydration Guardrail - Enforces strict architectural boundaries across the Nuxt 4 directory layout (app/, server/, and shared/) to prevent cross-request SSR state pollution and runtime hydration mismatches. Mandates request-scoped context within Nitro event handlers and restricts the shared/ layer to stateless, isomorphic code.
globs: app/**/*.{ts,vue}, server/**/*.{ts,js}, shared/**/*.{ts,js}, nuxt.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nuxt4-nitro-shared-ssr-state-isolation-production-standard"
---

# Nuxt 4 Nitro Server Engine Isolation & Shared Directory Hydration Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Leaks via Global Module Scope in Nitro Handlers and Isomorphic Boundary Violations in Nuxt 4 shared/

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 structural isolation and Nitro v2/v3 execution boundaries. You must reject any global mutable state in Nitro server handlers, prevent server-only or client-only API leakage into the shared/ directory, and ensure all SSR state hydration relies strictly on useState or event.context without cross-request memory leaks.

## Strict Guidelines
- Engineers MUST ALWAYS isolate state to the request lifecycle by using `useState()` in `app/` and `event.context` in `server/` handlers.
- Engineers MUST NOT declare top-level mutable variables (e.g., `let cache`, `const sessionStore = new Map()`) in `server/api/` or `server/routes/` as they persist across concurrent user requests in Node and Edge runtimes.
- The `shared/` directory MUST remain purely isomorphic and side-effect-free, containing only pure functions, schema validators (e.g., Zod), and shared TypeScript interfaces.
- Engineers MUST NOT import Node.js built-ins (`fs`, `crypto`, `path`), Nitro-specific symbols (`defineEventHandler`, `getCookie`), or Vue reactivity primitives (`ref`, `reactive`, `computed`) inside `shared/`.
- Nitro server routes MUST use `nitroStorage` or an external cache engine (e.g., Redis via `useStorage()`) instead of in-memory singletons for multi-tenant data caching.
- Components NEVER store per-request server data in standard module-scoped variables; all SSR data fetched from Nitro endpoints MUST be wrapped in `useAsyncData` or `useFetch` with unique, stable keys to guarantee idempotent hydration.

## Bad vs Good Implementations
### Cross-Request State Leak in Nitro Server Handler vs Request-Scoped Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-level mutable state in Nitro handlers is shared across all concurrent incoming HTTP requests on a persistent Node.js or Edge process, causing severe cross-request data leaks and privilege escalation bugs.
```typescript
// server/api/user-profile.ts
// CRITICAL BUG: Module-scoped variable persists across concurrent HTTP requests in long-lived Node/Nitro processes.
let userSession: { id: string; role: string } | null = null;

export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'Authorization');
  if (token) {
    userSession = await verifyAuthToken(token);
  }
  // Subsequent requests from OTHER users without a valid token will read the previous user's session
  return { user: userSession };
});
```

#### Production Standard (Correct)
> **Standard**: Attaching request-specific data directly to `event.context` guarantees that user identity is completely isolated to that single HTTP request and garbage-collected upon response completion.
```typescript
// server/api/user-profile.ts
export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'Authorization');
  if (!token) {
    throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
  }

  // Request-scoped through event context; destroyed when the HTTP response completes
  event.context.user = await verifyAuthToken(token);

  return {
    user: event.context.user
  };
});
```

### Isomorphic Directory Boundary Violation vs Shared Pure Contracts

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Importing Node.js core libraries or Vue-specific state primitives in the shared/ directory breaks isomorphic portability, causing bundler failures when resolved in browser contexts and memory leaks when instantiated globally during SSR.
```typescript
// shared/utils/user.ts
import { ref } from 'vue'; // VIOLATION: Framework client primitive in shared boundary
import fs from 'node:fs';   // VIOLATION: Node runtime primitive leaking to browser bundle

export const currentUserState = ref(null);

export function readConfig() {
  return JSON.parse(fs.readFileSync('/etc/app/config.json', 'utf8'));
}
```

#### Production Standard (Correct)
> **Standard**: The shared/ directory strictly holds platform-agnostic, side-effect-free code: schema definitions, contracts, and pure functional transforms executable identically in Nitro server and Vue browser environments.
```typescript
// shared/types/user.ts
import { z } from 'zod';

export const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  role: z.enum(['admin', 'member', 'guest'])
});

export type User = z.infer<typeof UserSchema>;

// shared/utils/format.ts
export function formatDisplayName(user: Pick<User, 'email'>): string {
  return user.email.split('@')[0] ?? 'Unknown';
}
```

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: Nuxt 4 Nitro Server Engine Isolation & Shared Directory Hydration Guardrail

Nuxt 4 Nitro Server Engine Isolation & Shared Directory Hydration Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces strict architectural boundaries across the Nuxt 4 directory layout (app/, server/, and shared/) to prevent cross-request SSR state pollution and runtime hydration mismatches. Mandates request-scoped context within Nitro event handlers and restricts the shared/ layer to stateless, isomorphic code. 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-Request State Leaks via Global Module Scope in Nitro Handlers and Isomorphic Boundary Violations in Nuxt 4 shared/ 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-Request State Leaks via Global Module Scope in Nitro Handlers and Isomorphic Boundary Violations in Nuxt 4 shared/Critical
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 isolate state to the request lifecycle by using `useState()` in `app/` and `event.context` in `server/` handlers.

Engineers MUST ALWAYS isolate state to the request lifecycle by using `useState()` in `app/` and `event.context` in `server/` handlers.

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 declare top-level mutable variables (e.g., `let cache`, `const sessionStore = new Map()`) in `server/api/` or `server/routes/` as they persist across concurrent user requests in Node and Edge runtimes.

Engineers MUST NOT declare top-level mutable variables (e.g., `let cache`, `const sessionStore = new Map()`) in `server/api/` or `server/routes/` as they persist across concurrent user requests in Node and Edge runtimes.

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

The `shared/` directory MUST remain purely isomorphic and side-effect-free, containing only pure functions, schema validators (e.g., Zod), and shared TypeScript interfaces.

The `shared/` directory MUST remain purely isomorphic and side-effect-free, containing only pure functions, schema validators (e.g., Zod), and shared TypeScript interfaces.

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 import Node.js built-ins (`fs`, `crypto`, `path`), Nitro-specific symbols (`defineEventHandler`, `getCookie`), or Vue reactivity primitives (`ref`, `reactive`, `computed`) inside `shared/`.

Engineers MUST NOT import Node.js built-ins (`fs`, `crypto`, `path`), Nitro-specific symbols (`defineEventHandler`, `getCookie`), or Vue reactivity primitives (`ref`, `reactive`, `computed`) inside `shared/`.

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

Nitro server routes MUST use `nitroStorage` or an external cache engine (e.g., Redis via `useStorage()`) instead of in-memory singletons for multi-tenant data caching.

Nitro server routes MUST use `nitroStorage` or an external cache engine (e.g., Redis via `useStorage()`) instead of in-memory singletons for multi-tenant data caching.

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 store per-request server data in standard module-scoped variables

Components NEVER store per-request server data in standard module-scoped variables; all SSR data fetched from Nitro endpoints MUST be wrapped in `useAsyncData` or `useFetch` with unique, stable keys to guarantee idempotent hydration.

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 Nuxt 4 Nitro Server Engine Isolation & Shared Directory Hydration Guardrail critical for AI coding assistants?

Enforces strict architectural boundaries across the Nuxt 4 directory layout (app/, server/, and shared/) to prevent cross-request SSR state pollution and runtime hydration mismatches. Mandates request-scoped context within Nitro event handlers and restricts the shared/ layer to stateless, isomorphic code. 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-Request State Leaks via Global Module Scope in Nitro Handlers and Isomorphic Boundary Violations in Nuxt 4 shared/) 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

Nuxt