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

Nuxt 4 Nitro Server Engine Isolation & Shared Directory State Guardrails

Nuxt 4 restructures application architecture by placing userland Vue code inside 'app/' while running server code via Nitro under 'server/'. Cross-boundary imports, direct Node.js runtime imports in the 'shared/' directory, and global module-level mutable state in Nitro handlers cause cross-request state pollution, SSR hydration mismatches, and build failures across non-Node deployment runtimes.

Prohibited Anti-Pattern: Cross-Request State Contamination via Global Nitro Variables and Unsafe Shared Directory Runtime Imports

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Server Engine Isolation & Shared Directory State Guardrails - Nuxt 4 restructures application architecture by placing userland Vue code inside 'app/' while running server code via Nitro under 'server/'. Cross-boundary imports, direct Node.js runtime imports in the 'shared/' directory, and global module-level mutable state in Nitro handlers cause cross-request state pollution, SSR hydration mismatches, and build failures across non-Node deployment runtimes.
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/nuxt-4-nitro-shared-directory-isolation"
---

# Nuxt 4 Nitro Server Engine Isolation & Shared Directory State Guardrails

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Contamination via Global Nitro Variables and Unsafe Shared Directory Runtime Imports

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 architectural boundaries, Nitro v2 server engine safety, and strict SSR state isolation. Enforce absolute separation between 'app/' (client/Vue SSR), 'server/' (Nitro runtime), and 'shared/' (isomorphic runtime-agnostic code). Prohibit global module-level state in Nitro handlers to eliminate cross-request memory leaks and multi-tenant data contamination. Enforce 'useState' or request-scoped context (event.context) for state hydration, and disallow platform-specific Node or Browser API calls in isomorphic modules.

## Strict Guidelines
- Engineers MUST ALWAYS isolate request-specific data inside Nitro event handlers by attaching state directly to 'event.context' rather than top-level module variables.
- Engineers MUST ALWAYS restrict modules in 'shared/' to pure, deterministic code that contains zero Node.js built-ins (e.g., 'fs', 'crypto', 'path') or browser globals (e.g., 'window', 'document', 'localStorage').
- Engineers MUST NEVER import code from 'server/' inside 'app/' or 'shared/', as this leaks server secrets, breaks client bundle tree-shaking, and causes runtime compilation failures.
- Engineers MUST use 'useState()' for state initialized on the server and hydrated on the client, NEVER standard Vue 'ref()' or 'reactive()' at the root of Nuxt plugins or outside Vue component setup lifecycles during SSR.
- Nitro route handlers MUST return serializable data types conforming to standard JSON specs to prevent hydration mismatches and devalue serialization crashes during HTML payload generation.
- Engineers MUST ensure that any runtime configuration required across client and server boundaries is accessed exclusively via 'useRuntimeConfig(event)' on Nitro and 'useRuntimeConfig()' within Vue setup contexts.

## Bad vs Good Implementations
### Module-Level Mutable State in Nitro Event Handler (Cross-Request Leak)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-level variables in Nitro server routes persist in memory across concurrent incoming requests in persistent Node or serverless container workers. This causes severe multi-tenant state leaks and race conditions.
```typescript
// server/api/user-session.ts
import { defineEventHandler, getQuery } from 'h3';

// ANTI-PATTERN: Shared module-level state persists across different incoming requests
let currentUserSession: { id: string; role: string } | null = null;

export default defineEventHandler((event) => {
  const query = getQuery(event);
  if (query.userId) {
    currentUserSession = { id: query.userId as string, role: 'member' };
  }
  // CRITICAL: Request B will read Request A's session data if query.userId is missing
  return { session: currentUserSession };
});
```

#### Production Standard (Correct)
> **Standard**: State is scoped explicitly to the current incoming H3Event context. It is destroyed when the request terminates, guaranteeing complete multi-tenant memory isolation.
```typescript
// server/api/user-session.ts
import { defineEventHandler, getQuery, createError } from 'h3';

interface UserSession {
  id: string;
  role: string;
}

declare module 'h3' {
  interface H3EventContext {
    session?: UserSession;
  }
}

export default defineEventHandler((event) => {
  const query = getQuery(event);
  const userId = query.userId as string | undefined;

  if (!userId) {
    throw createError({
      statusCode: 400,
      statusMessage: 'User ID is required'
    });
  }

  // Request-isolated state bound to the single H3 event lifecycle
  event.context.session = {
    id: userId,
    role: 'member'
  };

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

### Shared Directory Node.js Pollution and SSR Hydration State Mismatch

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Importing 'node:buffer' into the 'shared/' directory breaks client-side compilation and non-Node edge runtimes (e.g., Cloudflare Workers). Using a top-level Vue 'ref' in a composable leaks SSR state between distinct clients and breaks client hydration.
```typescript
// shared/utils/formatter.ts
import { Buffer } from 'node:buffer'; // ANTI-PATTERN: Node-specific runtime API in shared/

export function encodeUserToken(id: string): string {
  return Buffer.from(id).toString('base64');
}

// app/composables/useProfile.ts
import { ref } from 'vue';
import { encodeUserToken } from '~~/shared/utils/formatter';

// ANTI-PATTERN: Global ref leaks state across SSR requests and desyncs client hydration
const globalProfile = ref<string | null>(null);

export function useProfile(userId: string) {
  if (!globalProfile.value) {
    globalProfile.value = encodeUserToken(userId);
  }
  return { globalProfile };
}
```

#### Production Standard (Correct)
> **Standard**: The 'shared/' directory uses platform-agnostic web APIs. In Vue userland ('app/'), 'useState' replaces top-level 'ref', creating request-scoped, hydratable state that serializes safely without memory leakage across server renders.
```typescript
// shared/utils/formatter.ts
// Isomorphic implementation using web standard APIs safe for browser, edge, and node
export function encodeUserToken(id: string): string {
  if (typeof globalThis.btoa === 'function') {
    return globalThis.btoa(encodeURIComponent(id));
  }
  // Universal fallback without pulling platform-locked globals
  return encodeURIComponent(id);
}

// app/composables/useProfile.ts
import { useState } from 'nuxt/app';
import { encodeUserToken } from '~~/shared/utils/formatter';

export function useProfile(userId: string) {
  // useState is SSR-safe, serializes to the Nuxt payload, and guarantees request-isolation
  const profile = useState<string>(`profile-${userId}`, () => {
    return encodeUserToken(userId);
  });

  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 Server Engine Isolation & Shared Directory State Guardrails

Nuxt 4 Nitro Server Engine Isolation & Shared Directory State Guardrails defines an industrial-grade behavioral standard for frontend engineering. Nuxt 4 restructures application architecture by placing userland Vue code inside 'app/' while running server code via Nitro under 'server/'. Cross-boundary imports, direct Node.js runtime imports in the 'shared/' directory, and global module-level mutable state in Nitro handlers cause cross-request state pollution, SSR hydration mismatches, and build failures across non-Node deployment runtimes. 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 via Global Nitro Variables and Unsafe Shared Directory Runtime 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 DriftCross-Request State Contamination via Global Nitro Variables and Unsafe Shared Directory Runtime 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 isolate request-specific data inside Nitro event handlers by attaching state directly to 'event.context' rather than top-level module variables.

Engineers MUST ALWAYS isolate request-specific data inside Nitro event handlers by attaching state directly to 'event.context' rather than top-level module variables.

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 ALWAYS restrict modules in 'shared/' to pure, deterministic code that contains zero Node.js built-ins (e.g., 'fs', 'crypto', 'path') or browser globals (e.g., 'window', 'document', 'localStorage').

Engineers MUST ALWAYS restrict modules in 'shared/' to pure, deterministic code that contains zero Node.js built-ins (e.g., 'fs', 'crypto', 'path') or browser globals (e.g., 'window', 'document', 'localStorage').

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 import code from 'server/' inside 'app/' or 'shared/', as this leaks server secrets, breaks client bundle tree-shaking, and causes runtime compilation failures.

Engineers MUST NEVER import code from 'server/' inside 'app/' or 'shared/', as this leaks server secrets, breaks client bundle tree-shaking, and causes runtime compilation failures.

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 use 'useState()' for state initialized on the server and hydrated on the client, NEVER standard Vue 'ref()' or 'reactive()' at the root of Nuxt plugins or outside Vue component setup lifecycles during SSR.

Engineers MUST use 'useState()' for state initialized on the server and hydrated on the client, NEVER standard Vue 'ref()' or 'reactive()' at the root of Nuxt plugins or outside Vue component setup lifecycles 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

Nitro route handlers MUST return serializable data types conforming to standard JSON specs to prevent hydration mismatches and devalue serialization crashes during HTML payload generation.

Nitro route handlers MUST return serializable data types conforming to standard JSON specs to prevent hydration mismatches and devalue serialization crashes during HTML payload generation.

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 ensure that any runtime configuration required across client and server boundaries is accessed exclusively via 'useRuntimeConfig(event)' on Nitro and 'useRuntimeConfig()' within Vue setup contexts.

Engineers MUST ensure that any runtime configuration required across client and server boundaries is accessed exclusively via 'useRuntimeConfig(event)' on Nitro and 'useRuntimeConfig()' within Vue setup contexts.

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 State Guardrails critical for AI coding assistants?

Nuxt 4 restructures application architecture by placing userland Vue code inside 'app/' while running server code via Nitro under 'server/'. Cross-boundary imports, direct Node.js runtime imports in the 'shared/' directory, and global module-level mutable state in Nitro handlers cause cross-request state pollution, SSR hydration mismatches, and build failures across non-Node deployment runtimes. 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 via Global Nitro Variables and Unsafe Shared Directory Runtime 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