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

Nuxt 4 Nitro Server Engine Isolation and Shared Directory Invariants

Nuxt 4 transitions to an explicit `app/` directory root and introduces the top-level `shared/` directory alongside the Nitro v2 engine. Un-isolated module-level state in Nitro event handlers or leaking client-side reactive state into server runtime scopes causes cross-request pollution and catastrophic SSR state hydration mismatches.

Prohibited Anti-Pattern: Cross-Request State Leaks and Illegal Runtime Boundary Imports in Nuxt 4 / Nitro

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Server Engine Isolation and Shared Directory Invariants - Nuxt 4 transitions to an explicit `app/` directory root and introduces the top-level `shared/` directory alongside the Nitro v2 engine. Un-isolated module-level state in Nitro event handlers or leaking client-side reactive state into server runtime scopes causes cross-request pollution and catastrophic SSR state hydration mismatches.
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-architecture"
---

# Nuxt 4 Nitro Server Engine Isolation and Shared Directory Invariants

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Leaks and Illegal Runtime Boundary Imports in Nuxt 4 / Nitro

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 architectural boundaries and Nitro engine isolation. Mandate strict directory isolation between `app/`, `server/`, and `shared/`. Prevent cross-request state pollution in Nitro event handlers, eliminate invalid isomorphic imports, and ensure zero-leak SSR hydration states.

## Strict Guidelines
- Engineers MUST ALWAYS isolate request-scoped state within `event.context` in Nitro handlers rather than global/module-scoped variables to prevent cross-request leakage across concurrent SSR executions.
- Engineers MUST NOT import Vue runtime primitives (e.g., `ref`, `reactive`, `computed`) or DOM-dependent utilities into the `server/` or `shared/` directories unless explicitly intended for pure data transformations.
- Code placed in `shared/` MUST be strictly isomorphic, side-effect free, and limited to pure types, utility functions, validation schemas (e.g., Zod/Valibot), and universal constants.
- Services in `app/` MUST consume shared utilities through direct alias imports (e.g., `#shared`) rather than relative traversal escapes into server directories (e.g., `../../server`).
- Components NEVER store fetched state in module-scoped variables; dynamic server-rendered client state MUST strictly rely on `useState()` or Pinia stores bound to the active Nuxt SSR instance.

## Bad vs Good Implementations
### Nitro Server Handler Request State Isolation vs Module-Level Leaks

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Global and module-scoped variables persist in memory across requests in long-lived server processes (Node.js/Bun/Workers). Storing request-derived state like currentUserCache leaks sensitive user data across concurrent incoming requests.
```typescript
// server/api/user.ts
// ANTI-PATTERN: Module-scoped state leaks across concurrent tenant requests
let currentUserCache: Record<string, any> = {};

export default defineEventHandler(async (event) => {
  const authHeader = getHeader(event, 'authorization');
  if (authHeader) {
    currentUserCache['active'] = await verifyToken(authHeader);
  }
  return { user: currentUserCache['active'] };
});
```

#### Production Standard (Correct)
> **Standard**: H3 event contexts are instantiated per HTTP request and garbage collected when the request completes, guaranteeing absolute request isolation and zero cross-tenant contamination.
```typescript
// server/api/user.ts
// INVARIANT: Request-scoped state isolated within H3 event.context
export default defineEventHandler(async (event) => {
  const authHeader = getHeader(event, 'authorization');
  
  if (!authHeader) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized'
    });
  }

  // Attach ephemeral per-request state to event.context
  event.context.user = await verifyToken(authHeader);
  
  return {
    user: event.context.user
  };
});
```

### Nuxt 4 Shared Directory Data Validation Boundary

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Relative traversal into `server/` leaks backend dependencies into the client bundle and breaks Nuxt 4 tree-shaking. Module-level `cachedProfile` causes universal SSR state poisoning across all connected clients.
```typescript
// app/composables/useProfile.ts
// ANTI-PATTERN: Importing Nitro-internal utility and using global mutable variable
import { parseServerSession } from '../../server/utils/session';

let cachedProfile: any = null;

export const useProfile = () => {
  const load = async () => {
    if (!cachedProfile) {
      cachedProfile = await $fetch('/api/profile');
    }
    return cachedProfile;
  };
  return { load };
};
```

#### Production Standard (Correct)
> **Standard**: Pure isomorphic contracts and schemas reside in `shared/` imported via `#shared`. The composable uses `useState` which serializes cleanly from Nitro to the client payload without leakage across SSR runs.
```typescript
// shared/types/profile.ts
import { z } from 'zod';

export const ProfileSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  name: z.string().min(1)
});
export type Profile = z.infer<typeof ProfileSchema>;

// app/composables/useProfile.ts
import { type Profile, ProfileSchema } from '#shared/types/profile';

export const useProfile = () => {
  // Hydration-safe state isolated to Nuxt SSR instance
  const profile = useState<Profile | null>('user-profile', () => null);

  const fetchProfile = async () => {
    const data = await $fetch('/api/profile');
    const parsed = ProfileSchema.safeParse(data);
    if (parsed.success) {
      profile.value = parsed.data;
    }
  };

  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 Nitro Server Engine Isolation and Shared Directory Invariants

Nuxt 4 Nitro Server Engine Isolation and Shared Directory Invariants defines an industrial-grade behavioral standard for frontend engineering. Nuxt 4 transitions to an explicit `app/` directory root and introduces the top-level `shared/` directory alongside the Nitro v2 engine. Un-isolated module-level state in Nitro event handlers or leaking client-side reactive state into server runtime scopes causes cross-request pollution and catastrophic SSR state hydration mismatches. 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 and Illegal Runtime Boundary Imports in Nuxt 4 / Nitro 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 and Illegal Runtime Boundary Imports in Nuxt 4 / NitroCritical
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 request-scoped state within `event.context` in Nitro handlers rather than global/module-scoped variables to prevent cross-request leakage across concurrent SSR executions.

Engineers MUST ALWAYS isolate request-scoped state within `event.context` in Nitro handlers rather than global/module-scoped variables to prevent cross-request leakage across concurrent SSR executions.

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 Vue runtime primitives (e.g., `ref`, `reactive`, `computed`) or DOM-dependent utilities into the `server/` or `shared/` directories unless explicitly intended for pure data transformations.

Engineers MUST NOT import Vue runtime primitives (e.g., `ref`, `reactive`, `computed`) or DOM-dependent utilities into the `server/` or `shared/` directories unless explicitly intended for pure data transformations.

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

Code placed in `shared/` MUST be strictly isomorphic, side-effect free, and limited to pure types, utility functions, validation schemas (e.g., Zod/Valibot), and universal constants.

Code placed in `shared/` MUST be strictly isomorphic, side-effect free, and limited to pure types, utility functions, validation schemas (e.g., Zod/Valibot), and universal constants.

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

Services in `app/` MUST consume shared utilities through direct alias imports (e.g., `#shared`) rather than relative traversal escapes into server directories (e.g., `../../server`).

Services in `app/` MUST consume shared utilities through direct alias imports (e.g., `#shared`) rather than relative traversal escapes into server directories (e.g., `../../server`).

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

Components NEVER store fetched state in module-scoped variables

Components NEVER store fetched state in module-scoped variables; dynamic server-rendered client state MUST strictly rely on `useState()` or Pinia stores bound to the active Nuxt SSR instance.

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 and Shared Directory Invariants critical for AI coding assistants?

Nuxt 4 transitions to an explicit `app/` directory root and introduces the top-level `shared/` directory alongside the Nitro v2 engine. Un-isolated module-level state in Nitro event handlers or leaking client-side reactive state into server runtime scopes causes cross-request pollution and catastrophic SSR state hydration mismatches. 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 and Illegal Runtime Boundary Imports in Nuxt 4 / Nitro) 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