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

Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Hydration

Enforces strict architectural isolation across Nuxt 4 app/, server/, and shared/ directory boundaries to prevent cross-request state pollution in Nitro and SSR hydration mismatches. Prohibits module-scoped state in Nitro route handlers and guarantees shared/ contains only runtime-agnostic, side-effect-free code devoid of server secrets or client-only APIs.

Prohibited Anti-Pattern: Module-Level Nitro State Leakage and Shared Directory Secret Contamination Causing SSR Hydration Mismatches

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Hydration - Enforces strict architectural isolation across Nuxt 4 app/, server/, and shared/ directory boundaries to prevent cross-request state pollution in Nitro and SSR hydration mismatches. Prohibits module-scoped state in Nitro route handlers and guarantees shared/ contains only runtime-agnostic, side-effect-free code devoid of server secrets or client-only APIs.
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-guardrail"
---

# Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Hydration

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Module-Level Nitro State Leakage and Shared Directory Secret Contamination Causing SSR Hydration Mismatches

## System Constraints
You are a Principal Software Architect enforcing production safety in Nuxt 4 applications. You must strictly govern the tripartite directory model (app/, server/, shared/), eradicate cross-request state pollution in Nitro event handlers, prevent server secret leaks via shared code, and eliminate SSR hydration corruption caused by unpinned or non-serializable state.

## Strict Guidelines
- Engineers MUST ALWAYS isolate Nitro request state using `event.context` or explicit parameters; NEVER declare mutable module-scoped variables (`let`, `new Map()`, `ref()`) inside `server/` routes, utilities, or middleware.
- Engineers MUST confine all client-side Vue source files to the `app/` directory (e.g., `app/pages`, `app/components`, `app/composables`), keeping `server/` strictly for Nitro APIs, tasks, and middleware.
- Engineers MUST keep the `shared/` directory 100% runtime-agnostic and free of side effects; NEVER import `vue`, Node.js built-ins (`fs`, `crypto`, `path`), Nitro runtime utilities, or server runtime config into `shared/`.
- Engineers MUST ALWAYS manage SSR-hydrated reactive state with `useState(key, init)` in `app/composables/`; module-level `ref()`, `reactive()`, or global singletons in app code MUST NEVER be used as they cause cross-request tenant data leaks during SSR.
- Engineers MUST guarantee all payloads returned by `server/api/*` and consumed by `useAsyncData` or `useFetch` are JSON-serializable primitives, plain objects, or arrays; NEVER serialize class instances, functions, circular structures, or un-sanitized server metadata.
- Engineers MUST pass an explicit and deterministic key to `useAsyncData` when invoked conditionally or dynamically to prevent mismatching hydration states between SSR rendering and client-side mount.

## Bad vs Good Implementations
### Nitro Server Route State Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-scoped variables in Nitro persist across concurrent requests on Node.js and long-running serverless workers. Caching user sessions in module scope causes catastrophic cross-request state contamination where Request B receives credentials or state loaded by Request A.
```typescript
// server/api/user/session.ts
// FATAL: Module-scoped state shared across all concurrent requests (cross-tenant leak)
let activeSessionCache: Record<string, any> = {};

export default defineEventHandler(async (event) => {
  const authHeader = getHeader(event, 'authorization');
  if (!authHeader) throw createError({ statusCode: 401 });
  
  if (!activeSessionCache[authHeader]) {
    activeSessionCache[authHeader] = await fetchSessionFromDB(authHeader);
  }
  
  return activeSessionCache[authHeader];
});
```

#### Production Standard (Correct)
> **Standard**: Attaching intermediate state to `event.context` guarantees strict request lifecycles. Once the Nitro HTTP response terminates, the context is garbage-collected, preventing data leakage across concurrent server connections.
```typescript
// server/api/user/session.ts
// SECURE: Stateless handler binding request-scoped data to Nitro event context
export default defineEventHandler(async (event) => {
  const authHeader = getHeader(event, 'authorization');
  if (!authHeader) {
    throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
  }

  // Per-request isolation via event.context, or Nitro useStorage() with proper key isolation
  if (!event.context.userSession) {
    const session = await fetchSessionFromDB(authHeader);
    event.context.userSession = session;
  }

  return event.context.userSession;
});
```

### Nuxt 4 Shared Directory Boundaries & SSR State Hydration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: `shared/` is bundled into both client and Nitro output. Importing `node:crypto` and referencing `process.env.SERVER_SECRET` breaks client builds or leaks production secrets to browser bundles. Additionally, module-level `ref` in composables leaks state between SSR requests.
```typescript
// shared/utils/user.ts
// FATAL: Leaks server environment secrets and imports Node built-in to code shared with client
import { createHmac } from 'node:crypto';

export const hashToken = (token: string) => {
  const secret = process.env.SERVER_SECRET || 'fallback';
  return createHmac('sha256', secret).update(token).digest('hex');
};

// app/composables/useUserProfile.ts
// FATAL: Module-level ref causes SSR cross-request memory leak and hydration mismatches
const globalProfile = ref<UserProfile | null>(null);

export const useUserProfile = () => {
  return { profile: globalProfile };
};
```

#### Production Standard (Correct)
> **Standard**: `shared/` contains only runtime-agnostic contracts, validation logic, and shared types. The composable uses `useState()` with a unique key, ensuring Vue's hydration pipeline captures and isolates state per SSR request without cross-tenant memory leaks.
```typescript
// shared/types/user.ts
// COMPLIANT: Pure TypeScript interfaces and runtime-agnostic schemas
export interface UserProfile {
  id: string;
  username: string;
  roles: readonly string[];
}

export const isValidUsername = (name: string): boolean => {
  return /^[a-zA-Z0-9_-]{3,16}$/.test(name);
};

// app/composables/useUserProfile.ts
// COMPLIANT: Request-scoped SSR state isolated with Nuxt useState
import type { UserProfile } from '~~/shared/types/user';

export const useUserProfile = () => {
  const profile = useState<UserProfile | null>('user-profile-key', () => null);
  return { profile };
};
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Hydration

Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Hydration defines an industrial-grade behavioral standard for frontend engineering. Enforces strict architectural isolation across Nuxt 4 app/, server/, and shared/ directory boundaries to prevent cross-request state pollution in Nitro and SSR hydration mismatches. Prohibits module-scoped state in Nitro route handlers and guarantees shared/ contains only runtime-agnostic, side-effect-free code devoid of server secrets or client-only APIs. 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: Module-Level Nitro State Leakage and Shared Directory Secret Contamination Causing SSR Hydration Mismatches 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 DriftModule-Level Nitro State Leakage and Shared Directory Secret Contamination Causing SSR Hydration MismatchesCritical
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 Nitro request state using `event.context` or explicit parameters

Engineers MUST ALWAYS isolate Nitro request state using `event.context` or explicit parameters; NEVER declare mutable module-scoped variables (`let`, `new Map()`, `ref()`) inside `server/` routes, utilities, or middleware.

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 confine all client-side Vue source files to the `app/` directory (e.g., `app/pages`, `app/components`, `app/composables`), keeping `server/` strictly for Nitro APIs, tasks, and middleware.

Engineers MUST confine all client-side Vue source files to the `app/` directory (e.g., `app/pages`, `app/components`, `app/composables`), keeping `server/` strictly for Nitro APIs, tasks, and middleware.

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 keep the `shared/` directory 100% runtime-agnostic and free of side effects

Engineers MUST keep the `shared/` directory 100% runtime-agnostic and free of side effects; NEVER import `vue`, Node.js built-ins (`fs`, `crypto`, `path`), Nitro runtime utilities, or server runtime config into `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.
4

Engineers MUST ALWAYS manage SSR-hydrated reactive state with `useState(key, init)` in `app/composables/`

Engineers MUST ALWAYS manage SSR-hydrated reactive state with `useState(key, init)` in `app/composables/`; module-level `ref()`, `reactive()`, or global singletons in app code MUST NEVER be used as they cause cross-request tenant data leaks during SSR.

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

Engineers MUST guarantee all payloads returned by `server/api/*` and consumed by `useAsyncData` or `useFetch` are JSON-serializable primitives, plain objects, or arrays

Engineers MUST guarantee all payloads returned by `server/api/*` and consumed by `useAsyncData` or `useFetch` are JSON-serializable primitives, plain objects, or arrays; NEVER serialize class instances, functions, circular structures, or un-sanitized server metadata.

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 pass an explicit and deterministic key to `useAsyncData` when invoked conditionally or dynamically to prevent mismatching hydration states between SSR rendering and client-side mount.

Engineers MUST pass an explicit and deterministic key to `useAsyncData` when invoked conditionally or dynamically to prevent mismatching hydration states between SSR rendering and client-side mount.

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

Enforces strict architectural isolation across Nuxt 4 app/, server/, and shared/ directory boundaries to prevent cross-request state pollution in Nitro and SSR hydration mismatches. Prohibits module-scoped state in Nitro route handlers and guarantees shared/ contains only runtime-agnostic, side-effect-free code devoid of server secrets or client-only APIs. 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 (Module-Level Nitro State Leakage and Shared Directory Secret Contamination Causing SSR Hydration Mismatches) 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