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

Nuxt 4 Nitro Server Engine, Shared Directory, and SSR State Isolation

Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ isomorphic layer. Prevents cross-request state pollution, runtime leakage of server-only secrets into client hydrations, and invalid cross-domain module imports.

Prohibited Anti-Pattern: Global Module-Level State in Nitro Handlers and Leakage of Server Logic via Shared Directory

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Server Engine, Shared Directory, and SSR State Isolation - Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ isomorphic layer. Prevents cross-request state pollution, runtime leakage of server-only secrets into client hydrations, and invalid cross-domain module imports.
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-state-isolation"
---

# Nuxt 4 Nitro Server Engine, Shared Directory, and SSR State Isolation

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Global Module-Level State in Nitro Handlers and Leakage of Server Logic via Shared Directory

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 architecture and Nitro v2 invariants. You must prevent cross-request state contamination in Nitro server handlers, mandate correct utilization of the Nuxt 4 app/ and shared/ directory structure, and guarantee SSR state hydration safety.

## Strict Guidelines
- Engineers MUST NEVER declare mutable state variables at the module root level in Nitro event handlers (server/*) or composables (app/composables/*), as persistent worker runtimes (Node.js/Bun/Cloudflare Workers) share module scopes across distinct client requests.
- Engineers MUST store request-scoped data exclusively within 'event.context' inside Nitro server middleware and routes.
- Engineers MUST restrict the top-level 'shared/' directory to purely isomorphic, side-effect-free code (runtime-agnostic data schemas, pure utility functions, and TypeScript types).
- Engineers MUST NOT import Nitro server packages (such as 'h3' or Node-specific modules) or Vue/Nuxt client reactivity primitives ('ref', 'computed', 'useState') inside the 'shared/' directory.
- Components and composables in 'app/' MUST use 'useState()' instead of global Vue 'ref()' singletons outside of component lifecycles to ensure per-request state hydration isolation during SSR.
- Engineers MUST structure all client application code within the 'app/' root directory (including 'app/components', 'app/composables', 'app/pages', 'app/layouts') in compliance with Nuxt 4 specifications.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring 'currentUserToken' at module root causes a severe race condition and security hole: subsequent concurrent incoming requests overwrite this variable while the previous request is awaiting 'fetchUserProfile', leaking one user's private data to another.
```typescript
// server/api/user.ts
import { defineEventHandler, getHeader } from 'h3';

// CRITICAL FLAW: Module-level state is shared across all concurrent requests in SSR/Nitro
let currentUserToken: string | undefined;

export default defineEventHandler(async (event) => {
  currentUserToken = getHeader(event, 'authorization');
  
  // Asynchronous pause allows concurrent requests to overwrite currentUserToken
  const userData = await fetchUserProfile(currentUserToken);
  
  return { user: userData };
});

async function fetchUserProfile(token?: string) {
  if (!token) throw new Error('Unauthorized');
  return { id: 123, token };
}
```

#### Production Standard (Correct)
> **Standard**: Variables are locally scoped to the event handler execution context and 'event.context', ensuring zero state leakage across concurrent incoming requests in long-lived runtime instances.
```typescript
// server/api/user.ts
import { defineEventHandler, getHeader, createError } from 'h3';

export default defineEventHandler(async (event) => {
  // Invariant: Request scope is strictly isolated per event invocation or bound to event.context
  const authorization = getHeader(event, 'authorization');

  if (!authorization) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized: Missing authorization header'
    });
  }

  // Isolate request lifecycle data within event.context if middleware forwarding is required
  event.context.authToken = authorization;

  const userData = await fetchUserProfile(event.context.authToken);
  return { user: userData };
});

async function fetchUserProfile(token: string) {
  return { id: 123, token };
}
```

### Nuxt 4 Shared Directory and Composables State Hydration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The 'shared/' directory in Nuxt 4 must remain purely isomorphic. Importing Vue reactivity or H3 types introduces invalid server/client boundary dependencies and risks cross-request memory leaks.
```typescript
// shared/types/auth.ts
// ANTI-PATTERN: Leaking Vue client reactivity and Nitro internals into isomorphic shared directory
import { ref } from 'vue';
import type { H3Event } from 'h3';

export const globalSession = ref<Record<string, unknown> | null>(null);

export function setSessionFromEvent(event: H3Event) {
  globalSession.value = event.context.session;
}
```

#### Production Standard (Correct)
> **Standard**: The contract in 'shared/' is completely agnostic to runtime frameworks, and the reactive state in 'app/' is initialized via Nuxt's SSR-safe 'useState' composite key, isolating hydration payloads per request.
```typescript
// shared/types/auth.ts
// INVARIANT: Pure TypeScript contract and schema, free of runtime-specific side effects
export interface UserSession {
  id: string;
  email: string;
  roles: readonly string[];
}

export function isValidSession(data: unknown): data is UserSession {
  return typeof data === 'object' && data !== null && 'id' in data && 'email' in data;
}

// app/composables/useSession.ts
// INVARIANT: Nuxt 4 app/ composable leveraging SSR hydration-safe useState key
import type { UserSession } from '~~/shared/types/auth';

export const useSession = () => {
  return useState<UserSession | null>('user-session', () => null);
};
```

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, Shared Directory, and SSR State Isolation

Nuxt 4 Nitro Server Engine, Shared Directory, and SSR State Isolation defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ isomorphic layer. Prevents cross-request state pollution, runtime leakage of server-only secrets into client hydrations, and invalid cross-domain module imports. 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: Global Module-Level State in Nitro Handlers and Leakage of Server Logic via Shared Directory 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 DriftGlobal Module-Level State in Nitro Handlers and Leakage of Server Logic via Shared DirectoryCritical
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 NEVER declare mutable state variables at the module root level in Nitro event handlers (server/*) or composables (app/composables/*), as persistent worker runtimes (Node.js/Bun/Cloudflare Workers) share module scopes across distinct client requests.

Engineers MUST NEVER declare mutable state variables at the module root level in Nitro event handlers (server/*) or composables (app/composables/*), as persistent worker runtimes (Node.js/Bun/Cloudflare Workers) share module scopes across distinct client 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.
2

Engineers MUST store request-scoped data exclusively within 'event.context' inside Nitro server middleware and routes.

Engineers MUST store request-scoped data exclusively within 'event.context' inside Nitro server middleware and routes.

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 restrict the top-level 'shared/' directory to purely isomorphic, side-effect-free code (runtime-agnostic data schemas, pure utility functions, and TypeScript types).

Engineers MUST restrict the top-level 'shared/' directory to purely isomorphic, side-effect-free code (runtime-agnostic data schemas, pure utility functions, and TypeScript types).

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 NOT import Nitro server packages (such as 'h3' or Node-specific modules) or Vue/Nuxt client reactivity primitives ('ref', 'computed', 'useState') inside the 'shared/' directory.

Engineers MUST NOT import Nitro server packages (such as 'h3' or Node-specific modules) or Vue/Nuxt client reactivity primitives ('ref', 'computed', 'useState') inside the 'shared/' directory.

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 and composables in 'app/' MUST use 'useState()' instead of global Vue 'ref()' singletons outside of component lifecycles to ensure per-request state hydration isolation during SSR.

Components and composables in 'app/' MUST use 'useState()' instead of global Vue 'ref()' singletons outside of component lifecycles to ensure per-request state hydration isolation 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.
6

Engineers MUST structure all client application code within the 'app/' root directory (including 'app/components', 'app/composables', 'app/pages', 'app/layouts') in compliance with Nuxt 4 specifications.

Engineers MUST structure all client application code within the 'app/' root directory (including 'app/components', 'app/composables', 'app/pages', 'app/layouts') in compliance with Nuxt 4 specifications.

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

Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ isomorphic layer. Prevents cross-request state pollution, runtime leakage of server-only secrets into client hydrations, and invalid cross-domain module imports. 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 (Global Module-Level State in Nitro Handlers and Leakage of Server Logic via Shared Directory) 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