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

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

Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directory architecture. Eliminates multi-tenant cross-request state pollution in Nitro v2 event handlers and SSR composables, ensuring hydration safety and runtime-agnostic isomorphic code.

Prohibited Anti-Pattern: Module-Level State Bleed and Cross-Boundary Runtime Contamination in Nuxt 4

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Engine, Shared Directory, and SSR State Isolation - Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directory architecture. Eliminates multi-tenant cross-request state pollution in Nitro v2 event handlers and SSR composables, ensuring hydration safety and runtime-agnostic isomorphic code.
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-ssr-isolation-standard"
---

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

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Module-Level State Bleed and Cross-Boundary Runtime Contamination in Nuxt 4

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 and Nitro v2 production standards. Nuxt 4 shifts the application code into 'app/', retains Nitro in 'server/', and introduces 'shared/' for runtime-agnostic code. You must mandate zero cross-request state leakage, strictly isolate server context from client hydration, and prevent illegal dependency imports across boundary tiers.

## Strict Guidelines
- Engineers MUST ALWAYS house UI logic inside 'app/' (components, composables, pages) and backend logic in 'server/' (api, middleware, plugins).
- Engineers MUST NEVER declare mutable module-level singletons (e.g., let, const store = ref(), new Map()) in 'server/' or 'app/' SSR code; all request-scoped state MUST be encapsulated in Nitro 'event.context' or Nuxt 'useState()'.
- Code placed in the 'shared/' directory MUST be strictly isomorphic and pure: it MUST NOT import runtime-specific packages such as 'vue', 'h3', 'nitropack', or Nuxt auto-imports ('#imports').
- Server routes MUST ALWAYS wrap event handlers in 'defineEventHandler()' and derive per-request identity, tokens, and telemetry strictly from 'event.context' or 'getRouterParam(event)'.
- Composables MUST NEVER initialize 'ref()' or 'reactive()' outside of an active Nuxt/Vue lifecycle context (e.g., top-level file scope), as this creates a shared singleton across concurrent SSR HTTP requests.
- Components NEVER read directly from Node.js globals ('process.env') or Nitro internals; they MUST consume server data through 'useFetch()' or 'useAsyncData()' with explicit serialization keys to ensure deterministic hydration.

## Bad vs Good Implementations
### Nitro Server Handler: Cross-Request State Leak vs. Per-Request Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-scope variables in Nitro persist across requests within the worker thread. Concurrent incoming requests overwrite and read 'currentUserSession', causing catastrophic multi-tenant data leaks.
```typescript
// server/api/user/profile.ts
import { defineEventHandler, getHeader } from 'h3';

// ANTI-PATTERN: Module-level mutable state leaks across concurrent tenant requests
let currentUserSession: { userId?: string; token?: string } = {};

export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'authorization');
  if (token) {
    currentUserSession = { token, userId: parseJwt(token).sub };
  }
  
  // Multi-tenant race condition: Request B can read Request A's identity
  const profile = await fetchUserProfile(currentUserSession.userId);
  return { profile };
});

function parseJwt(token: string) { return { sub: 'user_123' }; }
declare function fetchUserProfile(id?: string): Promise<any>;
```

#### Production Standard (Correct)
> **Standard**: Per-request isolation is enforced via local function scope and 'event.context'. Data is typed using schemas from 'shared/types/user' without leaking state between concurrent calls.
```typescript
// server/api/user/profile.ts
import { defineEventHandler, getHeader, createError } from 'h3';
import type { UserProfile } from '~~/shared/types/user';

export default defineEventHandler(async (event): Promise<{ profile: UserProfile }> => {
  // INVARIANT: State is isolated to the request lifecycle via event.context
  const authHeader = getHeader(event, 'authorization');
  if (!authHeader?.startsWith('Bearer ')) {
    throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
  }

  const token = authHeader.slice(7);
  const userId = parseJwt(token).sub;
  
  // Attach per-request context if downstream utilities require it
  event.context.auth = { userId, token };

  const profile = await fetchUserProfile(userId);
  return { profile };
});

function parseJwt(token: string) { return { sub: 'user_123' }; }
declare function fetchUserProfile(id: string): Promise<UserProfile>;
```

### Nuxt 4 Shared Directory: Framework Coupling vs. Isomorphic Purity

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The 'shared/' directory is compiled for both Nitro and browser targets. Importing '#imports' or Vue reactivity creates build failures on Nitro and pollutes shared pure utilities with UI runtime dependencies.
```typescript
// shared/utils/validators.ts
// ANTI-PATTERN: Importing Vue/Nuxt runtime internals into the shared directory
import { ref } from 'vue';
import { useCookie } from '#imports';

export const validationStatus = ref<string>('idle');

export function validateUsername(username: string): boolean {
  const authCookie = useCookie('auth_token'); // CRASHES inside Nitro runtime
  validationStatus.value = 'validating';
  return username.length >= 3 && !!authCookie.value;
}
```

#### Production Standard (Correct)
> **Standard**: The shared utility is completely pure, deterministic, and free of framework runtime imports, allowing safe isomorphic consumption in both 'server/' routes and 'app/' Vue components.
```typescript
// shared/utils/validators.ts
// INVARIANT: Shared directory contains pure, runtime-agnostic TypeScript logic
export interface ValidationResult {
  isValid: boolean;
  error?: string;
}

export function validateUsername(username: string, minLength = 3): ValidationResult {
  if (!username || username.trim().length < minLength) {
    return {
      isValid: false,
      error: `Username must be at least ${minLength} characters long.`
    };
  }
  return { isValid: true };
}
```

### Nuxt 4 Composable SSR Hydration: Leaked Singleton vs. Isolated useState

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring 'ref()' at top-level module scope causes that single reactive instance to be shared across every incoming SSR request on the server thread, causing hydration mismatches and cross-client state leaks.
```typescript
// app/composables/useSession.ts
import { ref } from 'vue';

// ANTI-PATTERN: Singleton initialized at module level in client/server hybrid
const sharedCounter = ref(0);

export const useSessionCounter = () => {
  const increment = () => { sharedCounter.value++; };
  return { sharedCounter, increment };
};
```

#### Production Standard (Correct)
> **Standard**: Using 'useState()' guarantees that each SSR render gets an isolated state bucket keyed uniquely, which is deterministically serialized and hydrated to the client without cross-tenant memory sharing.
```typescript
// app/composables/useSession.ts
export const useSessionCounter = () => {
  // INVARIANT: useState is SSR-isolated and safely serialized into client payload
  const counter = useState<number>('session_counter', () => 0);
  
  const increment = () => {
    counter.value++;
  };

  return {
    counter: readonly(counter),
    increment
  };
};
```

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

Nuxt 4 Nitro Engine, Shared Directory, and SSR State Isolation defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directory architecture. Eliminates multi-tenant cross-request state pollution in Nitro v2 event handlers and SSR composables, ensuring hydration safety and runtime-agnostic isomorphic code. 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 State Bleed and Cross-Boundary Runtime Contamination in Nuxt 4 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 State Bleed and Cross-Boundary Runtime Contamination in Nuxt 4Critical
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 house UI logic inside 'app/' (components, composables, pages) and backend logic in 'server/' (api, middleware, plugins).

Engineers MUST ALWAYS house UI logic inside 'app/' (components, composables, pages) and backend logic in 'server/' (api, middleware, plugins).

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 module-level singletons (e.g., let, const store = ref(), new Map()) in 'server/' or 'app/' SSR code

Engineers MUST NEVER declare mutable module-level singletons (e.g., let, const store = ref(), new Map()) in 'server/' or 'app/' SSR code; all request-scoped state MUST be encapsulated in Nitro 'event.context' or Nuxt 'useState()'.

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 the 'shared/' directory MUST be strictly isomorphic and pure

Code placed in the 'shared/' directory MUST be strictly isomorphic and pure: it MUST NOT import runtime-specific packages such as 'vue', 'h3', 'nitropack', or Nuxt auto-imports ('#imports').

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

Server routes MUST ALWAYS wrap event handlers in 'defineEventHandler()' and derive per-request identity, tokens, and telemetry strictly from 'event.context' or 'getRouterParam(event)'.

Server routes MUST ALWAYS wrap event handlers in 'defineEventHandler()' and derive per-request identity, tokens, and telemetry strictly from 'event.context' or 'getRouterParam(event)'.

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

Composables MUST NEVER initialize 'ref()' or 'reactive()' outside of an active Nuxt/Vue lifecycle context (e.g., top-level file scope), as this creates a shared singleton across concurrent SSR HTTP requests.

Composables MUST NEVER initialize 'ref()' or 'reactive()' outside of an active Nuxt/Vue lifecycle context (e.g., top-level file scope), as this creates a shared singleton across concurrent SSR HTTP 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.
6

Components NEVER read directly from Node.js globals ('process.env') or Nitro internals

Components NEVER read directly from Node.js globals ('process.env') or Nitro internals; they MUST consume server data through 'useFetch()' or 'useAsyncData()' with explicit serialization keys to ensure deterministic hydration.

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

Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directory architecture. Eliminates multi-tenant cross-request state pollution in Nitro v2 event handlers and SSR composables, ensuring hydration safety and runtime-agnostic isomorphic code. 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 State Bleed and Cross-Boundary Runtime Contamination in Nuxt 4) 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