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

Nuxt 4 Directory Separation, Nitro Context Isolation, and SSR Hydration Safeguards

Enforces strict architectural boundaries across Nuxt 4 directory layers (`app/`, `server/`, and `shared/`) while preventing multi-tenant cross-request state contamination in Nitro server engines. Eliminates hydration mismatches and secret leakage by restricting server-only modules and stateful closures during SSR execution.

Prohibited Anti-Pattern: Module-Level Mutable State in Nitro Handlers and Cross-Boundary Node/Client Code Imports

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Directory Separation, Nitro Context Isolation, and SSR Hydration Safeguards - Enforces strict architectural boundaries across Nuxt 4 directory layers (`app/`, `server/`, and `shared/`) while preventing multi-tenant cross-request state contamination in Nitro server engines. Eliminates hydration mismatches and secret leakage by restricting server-only modules and stateful closures during SSR execution.
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-boundary-ssr-isolation"
---

# Nuxt 4 Directory Separation, Nitro Context Isolation, and SSR Hydration Safeguards

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Module-Level Mutable State in Nitro Handlers and Cross-Boundary Node/Client Code Imports

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 directory structures, Nitro v2 execution integrity, and SSR state boundaries. You must strictly enforce the physical layer boundary between `app/` (Vue UI layer), `server/` (Nitro runtime), and `shared/` (pure universal code). You must eradicate cross-request state pollution caused by module-level state in Nitro event handlers and global Vue reactive states during SSR. Prevent Node-only code from leaking into client bundles and UI dependencies from polluting the Nitro runtime.

## Strict Guidelines
- Engineers MUST ALWAYS place client-side UI, components, composables, and pages within the `app/` directory pursuant to Nuxt 4 architecture.
- Engineers MUST NEVER declare mutable variables (e.g., `let`, `new Map()`, or top-level singletons) at Nitro module scope in `server/`, as Nitro's long-running worker threads share module memory across concurrent user requests.
- Engineers MUST attach request-scoped state exclusively to Nitro's `event.context` using typed H3 event augmentations.
- Engineers MUST ensure code located in `shared/` is strictly isomorphic, side-effect-free, and contains only pure runtime validation schemas, pure transformation functions, and universal TypeScript contracts.
- Engineers MUST NEVER import database drivers, server SDKs, environment secrets, or Nitro-specific packages (`h3`, `nitropack`) into `app/` or `shared/`.
- Engineers MUST ALWAYS wrap shared Vue reactive state in `useState(key, init)` rather than module-scoped `ref()` or `reactive()` to prevent cross-request SSR hydration state leakage.
- Engineers MUST NEVER invoke browser globals (`window`, `document`, `localStorage`) in `server/`, `shared/`, or root setup functions of `app/` without an explicit `import.meta.client` guard.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring `currentUserSession` in the module root creates a critical cross-request state leak. Nitro v2 workers stay alive across requests; any concurrent or subsequent request will inherit another user's session data.
```typescript
// server/api/user-session.get.ts
import { defineEventHandler, getQuery } from 'h3';

// CRITICAL SECURITY BUG: Module-level mutable state leaks across requests in persistent workers
let currentUserSession: { userId?: string; role?: string } = {};

export default defineEventHandler((event) => {
  const query = getQuery(event);
  if (query.userId) {
    currentUserSession = { userId: String(query.userId), role: 'authenticated' };
  }
  // Subsequent requests from other users will read the previous request's currentUserSession
  return { session: currentUserSession };
});
```

#### Production Standard (Correct)
> **Standard**: State is scoped strictly to the ephemeral `H3Event` lifecycle. Every request maintains complete isolation without risk of cross-tenant memory leakage.
```typescript
// server/api/user-session.get.ts
import { defineEventHandler, getQuery, createError } from 'h3';

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const userId = query.userId ? String(query.userId) : null;

  if (!userId) {
    throw createError({ statusCode: 400, statusMessage: 'Missing userId parameter' });
  }

  // Request-isolated computation using event.context
  event.context.user = {
    userId,
    role: 'authenticated',
    resolvedAt: Date.now()
  };

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

### Nuxt 4 Composables and Shared Boundary Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly importing `server/` code into `app/` breaches security and breaks client compilation. Storing the reactive state in a module-level `ref` causes SSR cross-user data leakage and hydration mismatch.
```typescript
// app/composables/useUserProfile.ts
import { ref } from 'vue';
import prisma from '~~/server/utils/prisma'; // FATAL: Bundles Node server ORM into client application

// CRITICAL SSR LEAK: Global ref persists on server memory across SSR requests
const globalProfile = ref<any>(null);

export const useUserProfile = () => {
  const fetchProfile = async (id: string) => {
    globalProfile.value = await prisma.user.findUnique({ where: { id } });
  };
  return { profile: globalProfile, fetchProfile };
};
```

#### Production Standard (Correct)
> **Standard**: Interfaces are properly extracted to `shared/`, the database access is restricted behind Nitro `/api/users/[id]`, and `useState()` is used to provide request-isolated SSR state hydration.
```typescript
// shared/types/user.ts - Pure isomorphic contract
export interface UserProfile {
  id: string;
  name: string;
}

// app/composables/useUserProfile.ts
import type { UserProfile } from '~~/shared/types/user';

export const useUserProfile = () => {
  // useState guarantees per-request SSR isolation and seamless client hydration
  const profile = useState<UserProfile | null>('user-profile-state', () => null);

  const fetchProfile = async (id: string) => {
    const { data, error } = await useFetch<UserProfile>(`/api/users/${id}`);
    if (!error.value && data.value) {
      profile.value = data.value;
    }
  };

  return { profile: readonly(profile), fetchProfile };
};
```

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 Directory Separation, Nitro Context Isolation, and SSR Hydration Safeguards

Nuxt 4 Directory Separation, Nitro Context Isolation, and SSR Hydration Safeguards defines an industrial-grade behavioral standard for frontend engineering. Enforces strict architectural boundaries across Nuxt 4 directory layers (`app/`, `server/`, and `shared/`) while preventing multi-tenant cross-request state contamination in Nitro server engines. Eliminates hydration mismatches and secret leakage by restricting server-only modules and stateful closures during SSR execution. 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 Mutable State in Nitro Handlers and Cross-Boundary Node/Client Code Imports 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 Mutable State in Nitro Handlers and Cross-Boundary Node/Client Code ImportsCritical
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 place client-side UI, components, composables, and pages within the `app/` directory pursuant to Nuxt 4 architecture.

Engineers MUST ALWAYS place client-side UI, components, composables, and pages within the `app/` directory pursuant to Nuxt 4 architecture.

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 NEVER declare mutable variables (e.g., `let`, `new Map()`, or top-level singletons) at Nitro module scope in `server/`, as Nitro's long-running worker threads share module memory across concurrent user requests.

Engineers MUST NEVER declare mutable variables (e.g., `let`, `new Map()`, or top-level singletons) at Nitro module scope in `server/`, as Nitro's long-running worker threads share module memory across concurrent user 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.
3

Engineers MUST attach request-scoped state exclusively to Nitro's `event.context` using typed H3 event augmentations.

Engineers MUST attach request-scoped state exclusively to Nitro's `event.context` using typed H3 event augmentations.

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 ensure code located in `shared/` is strictly isomorphic, side-effect-free, and contains only pure runtime validation schemas, pure transformation functions, and universal TypeScript contracts.

Engineers MUST ensure code located in `shared/` is strictly isomorphic, side-effect-free, and contains only pure runtime validation schemas, pure transformation functions, and universal TypeScript contracts.

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 NEVER import database drivers, server SDKs, environment secrets, or Nitro-specific packages (`h3`, `nitropack`) into `app/` or `shared/`.

Engineers MUST NEVER import database drivers, server SDKs, environment secrets, or Nitro-specific packages (`h3`, `nitropack`) into `app/` or `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.
6

Engineers MUST ALWAYS wrap shared Vue reactive state in `useState(key, init)` rather than module-scoped `ref()` or `reactive()` to prevent cross-request SSR hydration state leakage.

Engineers MUST ALWAYS wrap shared Vue reactive state in `useState(key, init)` rather than module-scoped `ref()` or `reactive()` to prevent cross-request SSR hydration state leakage.

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

Engineers MUST NEVER invoke browser globals (`window`, `document`, `localStorage`) in `server/`, `shared/`, or root setup functions of `app/` without an explicit `import.meta.client` guard.

Engineers MUST NEVER invoke browser globals (`window`, `document`, `localStorage`) in `server/`, `shared/`, or root setup functions of `app/` without an explicit `import.meta.client` guard.

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 Directory Separation, Nitro Context Isolation, and SSR Hydration Safeguards critical for AI coding assistants?

Enforces strict architectural boundaries across Nuxt 4 directory layers (`app/`, `server/`, and `shared/`) while preventing multi-tenant cross-request state contamination in Nitro server engines. Eliminates hydration mismatches and secret leakage by restricting server-only modules and stateful closures during SSR execution. 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 Mutable State in Nitro Handlers and Cross-Boundary Node/Client Code Imports) 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