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

Nuxt 4 Nitro Engine Boundary, Shared Directory Isolation, and SSR State Hydration Invariants

Enforces strict architectural boundaries across Nuxt 4 app/, server/, and shared/ directories. Eliminates cross-request state pollution in Nitro v2 server handlers and guarantees deterministic SSR state hydration without runtime secret leaks.

Prohibited Anti-Pattern: Cross-Request State Contamination, Server Leakage in Shared Directory, and Hydration Mismatches via Module-Scoped State

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Engine Boundary, Shared Directory Isolation, and SSR State Hydration Invariants - Enforces strict architectural boundaries across Nuxt 4 app/, server/, and shared/ directories. Eliminates cross-request state pollution in Nitro v2 server handlers and guarantees deterministic SSR state hydration without runtime secret leaks.
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-directory-isolation-standard"
---

# Nuxt 4 Nitro Engine Boundary, Shared Directory Isolation, and SSR State Hydration Invariants

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Contamination, Server Leakage in Shared Directory, and Hydration Mismatches via Module-Scoped State

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 architectural invariants across Nitro v2 server engines, the app/ directory, and the shared/ directory. You must strictly prevent cross-request SSR state leaks, ensure isolation between Nitro server runtime and Vue client runtime, and enforce clean shared contracts.

## Strict Guidelines
- Engineers MUST ALWAYS house application code in 'app/', Nitro server code in 'server/', and isomorphic code (types, schemas, pure utilities) strictly in 'shared/'.
- Engineers MUST NOT import server-specific code, node modules (e.g., 'fs', 'crypto', DB clients), or Nitro utilities into 'shared/' or 'app/'.
- Engineers MUST NEVER declare mutable state at the module level in Nitro server routes, event handlers, middleware, or client composables; module-scope variables are shared across all concurrent SSR requests.
- Engineers MUST ALWAYS use 'useState(key, init)' within composables to ensure SSR-to-client hydration state isolation and deterministic rehydration.
- Nitro route handlers MUST store request-scoped data strictly in 'event.context' and return serialized, JSON-safe data structures.
- Engineers MUST ALWAYS use H3's 'createError' with explicit 'statusCode' and sanitized 'statusMessage' in Nitro handlers, never throwing raw unhandled exceptions.
- Components NEVER execute server-only database drivers or direct Nitro runtime calls; all communication between 'app/' and 'server/' MUST occur through '$fetch' or 'useFetch' contracts referencing Nitro endpoints.

## Bad vs Good Implementations
### Preventing Module-Level State Pollution in Nitro v2 Server Routes

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring 'currentUserSession' at the module level creates cross-request state pollution. In persistent server runtimes (Node.js, Bun, Cloudflare Workers), module-level state persists across requests, causing critical security data leaks between users.
```typescript
// server/api/user/session.ts
// FATAL: Module-scoped state shared across concurrent requests on Node/Edge runtime
let currentUserSession: { userId?: string } = {}

export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'authorization')
  if (token) {
    currentUserSession.userId = await verifyToken(token)
  }
  // Subsequent requests from different users will read the previous user's session!
  return { session: currentUserSession }
})
```

#### Production Standard (Correct)
> **Standard**: State is completely isolated to the incoming request via 'event.context' and local block scope. It guarantees absolute memory safety between concurrent SSR requests and validates output using isomorphic contracts from 'shared/'.
```typescript
// server/api/user/session.ts
// PRODUCTION FIX: Pure request-scoped state stored in H3 event context
import { z } from 'zod'
import { SessionResponseSchema } from '~~/shared/types/auth'

export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'authorization')
  
  if (!token) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized: Missing authorization header'
    })
  }

  const userId = await verifyToken(token).catch(() => {
    throw createError({
      statusCode: 403,
      statusMessage: 'Forbidden: Invalid authorization token'
    })
  })

  // Store in H3 request context for downstream handlers/middleware
  event.context.auth = { userId }

  const response = {
    session: {
      userId: event.context.auth.userId,
      authenticatedAt: new Date().toISOString()
    }
  }

  return SessionResponseSchema.parse(response)
})
```

### Deterministic SSR Hydration in App Composables vs Un-isolated Ref

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using a module-scoped 'ref()' outside the composable factory causes all SSR server threads to share the same reactive pointer, leaking one client's profile data to another user during SSR rendering.
```typescript
// app/composables/useProfile.ts
// FATAL: Global ref causes memory leaks and cross-request SSR bleeding
const globalProfile = ref(null)

export const useProfile = () => {
  const fetchProfile = async () => {
    // Mutates shared instance in SSR server thread
    globalProfile.value = await $fetch('/api/profile')
  }
  return { profile: globalProfile, fetchProfile }
}
```

#### Production Standard (Correct)
> **Standard**: Using 'useState()' binds the reactive state to the current Nuxt SSR instance payload (`nuxtApp.payload.state`), ensuring multi-tenant safety during SSR rendering and flawless client-side hydration.
```typescript
// app/composables/useProfile.ts
// PRODUCTION FIX: Nuxt useState provides isolated SSR cache and deterministic hydration
import type { UserProfile } from '~~/shared/types/user'

export const useProfile = () => {
  // Deterministic, unique hydration key isolated per request during SSR
  const profile = useState<UserProfile | null>('user-profile-state', () => null)

  const { data, error, status, refresh } = useFetch<UserProfile>('/api/profile', {
    key: 'user-profile-fetch',
    default: () => null
  })

  // Sync useFetch deterministic response
  if (data.value && !profile.value) {
    profile.value = data.value
  }

  return {
    profile,
    status,
    error,
    refresh
  }
}
```

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 Engine Boundary, Shared Directory Isolation, and SSR State Hydration Invariants

Nuxt 4 Nitro Engine Boundary, Shared Directory Isolation, and SSR State Hydration Invariants defines an industrial-grade behavioral standard for frontend engineering. Enforces strict architectural boundaries across Nuxt 4 app/, server/, and shared/ directories. Eliminates cross-request state pollution in Nitro v2 server handlers and guarantees deterministic SSR state hydration without runtime secret leaks. 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 Contamination, Server Leakage in Shared Directory, and Hydration Mismatches via Module-Scoped State 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 Contamination, Server Leakage in Shared Directory, and Hydration Mismatches via Module-Scoped StateCritical
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 house application code in 'app/', Nitro server code in 'server/', and isomorphic code (types, schemas, pure utilities) strictly in 'shared/'.

Engineers MUST ALWAYS house application code in 'app/', Nitro server code in 'server/', and isomorphic code (types, schemas, pure utilities) strictly in '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.
2

Engineers MUST NOT import server-specific code, node modules (e.g., 'fs', 'crypto', DB clients), or Nitro utilities into 'shared/' or 'app/'.

Engineers MUST NOT import server-specific code, node modules (e.g., 'fs', 'crypto', DB clients), or Nitro utilities into 'shared/' or 'app/'.

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 NEVER declare mutable state at the module level in Nitro server routes, event handlers, middleware, or client composables

Engineers MUST NEVER declare mutable state at the module level in Nitro server routes, event handlers, middleware, or client composables; module-scope variables are shared across all concurrent SSR requests.

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 ALWAYS use 'useState(key, init)' within composables to ensure SSR-to-client hydration state isolation and deterministic rehydration.

Engineers MUST ALWAYS use 'useState(key, init)' within composables to ensure SSR-to-client hydration state isolation and deterministic rehydration.

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 route handlers MUST store request-scoped data strictly in 'event.context' and return serialized, JSON-safe data structures.

Nitro route handlers MUST store request-scoped data strictly in 'event.context' and return serialized, JSON-safe data structures.

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

Engineers MUST ALWAYS use H3's 'createError' with explicit 'statusCode' and sanitized 'statusMessage' in Nitro handlers, never throwing raw unhandled exceptions.

Engineers MUST ALWAYS use H3's 'createError' with explicit 'statusCode' and sanitized 'statusMessage' in Nitro handlers, never throwing raw unhandled exceptions.

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.
7

Components NEVER execute server-only database drivers or direct Nitro runtime calls

Components NEVER execute server-only database drivers or direct Nitro runtime calls; all communication between 'app/' and 'server/' MUST occur through '$fetch' or 'useFetch' contracts referencing Nitro endpoints.

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 Engine Boundary, Shared Directory Isolation, and SSR State Hydration Invariants critical for AI coding assistants?

Enforces strict architectural boundaries across Nuxt 4 app/, server/, and shared/ directories. Eliminates cross-request state pollution in Nitro v2 server handlers and guarantees deterministic SSR state hydration without runtime secret leaks. 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 Contamination, Server Leakage in Shared Directory, and Hydration Mismatches via Module-Scoped State) 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