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

Nuxt 4 Nitro Server Engine & Shared Directory State Isolation Standards

Enforces strict architectural boundaries and execution context isolation in Nuxt 4, isolating Nitro server engine logic from the app/ directory via the root shared/ boundary. Prevents catastrophic cross-request state pollution during SSR hydration, illegal cross-boundary runtime imports, and leaks of server-only secrets into client bundles.

Prohibited Anti-Pattern: Cross-Request SSR State Pollution via Nitro Module-Level Singletons and Direct App-to-Server Imports

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Server Engine & Shared Directory State Isolation Standards - Enforces strict architectural boundaries and execution context isolation in Nuxt 4, isolating Nitro server engine logic from the app/ directory via the root shared/ boundary. Prevents catastrophic cross-request state pollution during SSR hydration, illegal cross-boundary runtime imports, and leaks of server-only secrets into client bundles.
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-state-isolation"
---

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

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request SSR State Pollution via Nitro Module-Level Singletons and Direct App-to-Server Imports

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 production standards. You mandate absolute boundary isolation between the Nuxt 4 `app/` directory (Vue presentation runtime), `server/` directory (Nitro v2 engine), and `shared/` directory (universal zero-side-effect schemas and types). Enforce per-request context scoping in Nitro event handlers to prevent cross-request memory leaks and multi-tenant data contamination during SSR.

## Strict Guidelines
- Engineers MUST ALWAYS isolate universal contracts, Zod schemas, and pure utility functions into the root `shared/` directory, imported using the `~shared` or `#shared` alias.
- Engineers MUST NOT import any file from `server/` directly into `app/`, as this bypasses Nitro compilation barriers and risks bundling server secrets into client artifacts.
- Engineers MUST NEVER declare mutable state (e.g., `let cache = {}`, `const session = reactive({})`) in module scope within `server/api/*` or `server/middleware/*`; state MUST be explicitly scoped to `event.context` per request.
- Code MUST use `useState<T>()` exclusively within the Vue application lifecycle (`app/`) to avoid hydration mismatches, and MUST NEVER use `useState` inside Nitro handlers (`server/`).
- Nitro event handlers MUST return typed responses validated via `shared/` schemas, utilizing `readValidatedBody` or `getValidatedQuery` from `h3` rather than unvalidated accessors.
- Services interacting with external datasources MUST instantiate clients per request or utilize thread-safe connection pooling attached to Nitro runtime hooks via `nitroApp.hooks`.

## Bad vs Good Implementations
### Nitro Server Route State Pollution vs. Per-Request Context Scoping

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring mutable variables in module scope within Nitro handlers creates a shared singleton across all incoming HTTP requests. Under concurrent multi-user load, User B will read or overwrite User A's session context, leading to security breaches and cross-request state contamination.
```typescript
// server/api/user/profile.get.ts
import { defineEventHandler, getQuery } from 'h3';

// CRITICAL FLAW: Module-level mutable state leaks across concurrent requests in Nitro SSR engine
let currentUserSession: { userId?: string; role?: string } = {};

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  currentUserSession.userId = query.userId as string;
  currentUserSession.role = 'member';

  // Subsequent concurrent requests will read/overwrite this identical shared instance
  const profile = await fetchUserProfile(currentUserSession.userId);
  return { profile, session: currentUserSession };
});

async function fetchUserProfile(id: string) {
  return { id, name: 'Alice' };
}
```

#### Production Standard (Correct)
> **Standard**: Validates inputs strictly using the `#shared` schema contract and eliminates module singletons. Data is isolated to local scope and the `event.context` lifecycle, guaranteeing request hermeticity during SSR.
```typescript
// shared/types/user.ts
import { z } from 'zod';

export const UserProfileSchema = z.object({
  userId: z.string().uuid(),
  role: z.enum(['admin', 'member', 'guest'])
});
export type UserProfile = z.infer<typeof UserProfileSchema>;

// server/api/user/profile.get.ts
import { defineEventHandler, getValidatedQuery, createError } from 'h3';
import { UserProfileSchema } from '#shared/types/user';

export default defineEventHandler(async (event) => {
  // Invariant: Query parameters validated against shared schema, scoped strictly to the H3Event
  const query = await getValidatedQuery(event, (data) =>
    UserProfileSchema.pick({ userId: true }).safeParse(data)
  );

  if (!query.success) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Invalid userId parameter',
      data: query.error.format()
    });
  }

  // State is localized to the execution frame and event context
  const session = event.context.auth ?? { role: 'member' };
  const profile = await fetchUserProfile(query.data.userId);

  return {
    profile,
    role: session.role
  };
});

async function fetchUserProfile(id: string) {
  return { id, name: 'Alice' };
}
```

### Nuxt 4 Direct Cross-Boundary Import vs. Shared Directory Extraction

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Importing server-side utilities into the Nuxt 4 `app/` presentation tree breaks bundler tree-shaking, pulls Node.js-only dependencies into the browser bundle, and frequently leaks encryption algorithms, salts, or server database types directly to the client.
```typescript
// app/composables/useUser.ts
import { ref } from 'vue';
// CRITICAL ARCHITECTURAL VIOLATION: Importing directly from server directory into app runtime
import { hashPassword, decryptToken } from '../../server/utils/crypto';
import type { UserRecord } from '../../server/types/db';

export function useUser() {
  const user = ref<UserRecord | null>(null);
  const verifyClientSide = (pwd: string) => hashPassword(pwd);
  return { user, verifyClientSide };
}
```

#### Production Standard (Correct)
> **Standard**: Universal utilities are moved to `#shared`, ensuring no server-only runtime dependencies enter client bundles. SSR-compatible hydration state is handled strictly via Nuxt's `useState()` key-scoping.
```typescript
// shared/utils/validation.ts - Zero side-effects, safe for both client and Nitro
export const isValidUsername = (username: string): boolean => {
  return /^[a-zA-Z0-9_-]{3,16}$/.test(username);
};

// app/composables/useUser.ts
import { useState } from '#imports';
import { isValidUsername } from '#shared/utils/validation';

export interface ClientSafeUser {
  id: string;
  username: string;
}

export function useUser() {
  // Nuxt-safe SSR hydrated state
  const user = useState<ClientSafeUser | null>('user-state', () => null);

  const validate = (name: string): boolean => {
    return isValidUsername(name);
  };

  return { user, validate };
}
```

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 State Isolation Standards

Nuxt 4 Nitro Server Engine & Shared Directory State Isolation Standards defines an industrial-grade behavioral standard for frontend engineering. Enforces strict architectural boundaries and execution context isolation in Nuxt 4, isolating Nitro server engine logic from the app/ directory via the root shared/ boundary. Prevents catastrophic cross-request state pollution during SSR hydration, illegal cross-boundary runtime imports, and leaks of server-only secrets into client bundles. 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 SSR State Pollution via Nitro Module-Level Singletons and Direct App-to-Server 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 SSR State Pollution via Nitro Module-Level Singletons and Direct App-to-Server 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 universal contracts, Zod schemas, and pure utility functions into the root `shared/` directory, imported using the `~shared` or `#shared` alias.

Engineers MUST ALWAYS isolate universal contracts, Zod schemas, and pure utility functions into the root `shared/` directory, imported using the `~shared` or `#shared` alias.

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 any file from `server/` directly into `app/`, as this bypasses Nitro compilation barriers and risks bundling server secrets into client artifacts.

Engineers MUST NOT import any file from `server/` directly into `app/`, as this bypasses Nitro compilation barriers and risks bundling server secrets into client artifacts.

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 declare mutable state (e.g., `let cache = {}`, `const session = reactive({})`) in module scope within `server/api/*` or `server/middleware/*`

Engineers MUST NEVER declare mutable state (e.g., `let cache = {}`, `const session = reactive({})`) in module scope within `server/api/*` or `server/middleware/*`; state MUST be explicitly scoped to `event.context` per request.

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

Code MUST use `useState<T>()` exclusively within the Vue application lifecycle (`app/`) to avoid hydration mismatches, and MUST NEVER use `useState` inside Nitro handlers (`server/`).

Code MUST use `useState<T>()` exclusively within the Vue application lifecycle (`app/`) to avoid hydration mismatches, and MUST NEVER use `useState` inside Nitro handlers (`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

Nitro event handlers MUST return typed responses validated via `shared/` schemas, utilizing `readValidatedBody` or `getValidatedQuery` from `h3` rather than unvalidated accessors.

Nitro event handlers MUST return typed responses validated via `shared/` schemas, utilizing `readValidatedBody` or `getValidatedQuery` from `h3` rather than unvalidated accessors.

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

Services interacting with external datasources MUST instantiate clients per request or utilize thread-safe connection pooling attached to Nitro runtime hooks via `nitroApp.hooks`.

Services interacting with external datasources MUST instantiate clients per request or utilize thread-safe connection pooling attached to Nitro runtime hooks via `nitroApp.hooks`.

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

Enforces strict architectural boundaries and execution context isolation in Nuxt 4, isolating Nitro server engine logic from the app/ directory via the root shared/ boundary. Prevents catastrophic cross-request state pollution during SSR hydration, illegal cross-boundary runtime imports, and leaks of server-only secrets into client bundles. 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 SSR State Pollution via Nitro Module-Level Singletons and Direct App-to-Server 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