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

Nuxt 4 Nitro Server Engine Architecture & SSR State Isolation Standard

Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directories while eliminating cross-request state pollution in Nitro event handlers and Vue SSR composables. Mandates request-scoped context, unstorage/H3 event context over module-level singletons, and useState over global refs to prevent concurrent tenant data leakage.

Prohibited Anti-Pattern: Cross-Request State Contamination via Global Nitro Singletons and Illegal Directory Imports

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Server Engine Architecture & SSR State Isolation Standard - Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directories while eliminating cross-request state pollution in Nitro event handlers and Vue SSR composables. Mandates request-scoped context, unstorage/H3 event context over module-level singletons, and useState over global refs to prevent concurrent tenant data leakage.
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"
---

# Nuxt 4 Nitro Server Engine Architecture & SSR State Isolation Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Contamination via Global Nitro Singletons and Illegal Directory Imports

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 and Nitro v2 production standards. Nuxt 4 introduces a dedicated app/ directory structure, a shared/ directory for universal code, and strict boundaries around the Nitro server runtime. Your primary mandate is to prevent cross-request SSR state leakage (where global variables leak data between concurrent users) and eliminate illegal cross-boundary imports between server/ and app/.

## Strict Guidelines
- Engineers MUST configure 'future.compatibilityVersion: 4' in nuxt.config.ts and organize client/universal application code strictly inside the 'app/' directory.
- Engineers MUST place universal contracts, utilities, DTOs, and pure validation schemas in the root 'shared/' directory, never duplicating types across 'app/' and 'server/'.
- Engineers MUST NEVER import code from 'server/' into 'app/' or import Vue/client-specific composables from 'app/' into 'server/'.
- Engineers MUST NEVER declare mutable state in module/top-level scope within Nitro event handlers ('server/api/**' or 'server/routes/**') because Node.js/Nitro processes persist module scope across concurrent HTTP requests.
- Engineers MUST store request-scoped data exclusively on 'event.context' using Nitro middleware, or retrieve persisted server state via 'useStorage()'.
- Engineers MUST NEVER use global 'ref()' or 'reactive()' declarations outside of component setup or 'useState()' inside composables, as this creates a shared singleton across all SSR sessions.
- Engineers MUST use 'useState(key, init)' for client-server SSR state hydration to guarantee isolated state per SSR request lifecycle.

## Bad vs Good Implementations
### Nitro Server Handler: Module-Scoped Mutable State vs Request-Scoped Event Storage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-scoped variables in Nitro are shared across all incoming HTTP requests in a persistent server process. Under concurrent load, requests mutate and read the same shared memory, leaking tenant or user session data.
```typescript
// server/api/user-session.ts
import { defineEventHandler, getQuery } from 'h3';

// CRITICAL ANTI-PATTERN: Module-level state persists across requests in Node/Nitro.
// User B can view User A's profile if requests execute concurrently.
let currentUser: { id: string; role: string } | null = null;

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  if (query.userId) {
    currentUser = { id: query.userId as string, role: 'authenticated' };
  }
  return { user: currentUser };
});
```

#### Production Standard (Correct)
> **Standard**: State is retrieved purely within the event handler lifecycle and persisted via Nitro's storage layer or attached directly to event.context, ensuring complete isolation between concurrent requests.
```typescript
// server/api/user-session.ts
import { defineEventHandler, createError, getQuery } from 'h3';
import type { UserProfile } from '~~/shared/types/user';

export default defineEventHandler(async (event): Promise<{ user: UserProfile }> => {
  const query = getQuery(event);
  const userId = query.userId as string | undefined;

  if (!userId) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Missing required userId query parameter'
    });
  }

  // Request-scoped retrieval via event context or safe external store
  const storage = useStorage('data');
  const user = await storage.getItem<UserProfile>(`users:${userId}`);

  if (!user) {
    throw createError({
      statusCode: 404,
      statusMessage: 'User profile not found'
    });
  }

  return { user };
});
```

### Nuxt 4 Shared Directory and SSR-Safe Composable State

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring a Vue `ref()` outside the composable factory creates an SSR singleton shared between all concurrent user requests on the server. Furthermore, directly importing from `server/utils/db` breaks build isolation and risks leaking server secrets to the client bundle.
```typescript
// app/composables/useProfile.ts
import { ref } from 'vue';
// ANTI-PATTERN: Leaking server runtime into client/app directory
import { getDbConnection } from '~~/server/utils/db';

// CRITICAL ANTI-PATTERN: Module-level ref outside composable function.
// Persists across all SSR requests, polluting client hydration across users.
const profileState = ref<any>(null);

export const useProfile = () => {
  const fetchProfile = async (id: string) => {
    profileState.value = await getDbConnection().query(id);
  };
  return { profileState, fetchProfile };
};
```

#### Production Standard (Correct)
> **Standard**: Types are extracted to the root shared/ directory, preventing cross-boundary runtime imports. State is managed via `useState()` and `useFetch()`, ensuring deterministic per-request SSR instance isolation and safe hydration transfer.
```typescript
// shared/types/profile.ts
export interface UserProfileDto {
  id: string;
  name: string;
  email: string;
}

// app/composables/useProfile.ts
import type { UserProfileDto } from '~~/shared/types/profile';

export const useProfile = (userId: MaybeRefOrGetter<string>) => {
  // Invariant: useState scopes state to the NuxtApp instance and serializes for hydration
  const id = toValue(userId);
  const profile = useState<UserProfileDto | null>(`profile-${id}`, () => null);

  const { data, error, refresh } = useFetch<UserProfileDto>(`/api/profile/${id}`, {
    key: `profile-fetch-${id}`,
    default: () => null
  });

  return {
    profile: data,
    error,
    refresh
  };
};
```

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 Architecture & SSR State Isolation Standard

Nuxt 4 Nitro Server Engine Architecture & SSR State Isolation Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directories while eliminating cross-request state pollution in Nitro event handlers and Vue SSR composables. Mandates request-scoped context, unstorage/H3 event context over module-level singletons, and useState over global refs to prevent concurrent tenant data leakage. 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 Singletons and Illegal Directory 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 Singletons and Illegal Directory 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 configure 'future.compatibilityVersion

Engineers MUST configure 'future.compatibilityVersion: 4' in nuxt.config.ts and organize client/universal application code strictly inside the 'app/' 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.
2

Engineers MUST place universal contracts, utilities, DTOs, and pure validation schemas in the root 'shared/' directory, never duplicating types across 'app/' and 'server/'.

Engineers MUST place universal contracts, utilities, DTOs, and pure validation schemas in the root 'shared/' directory, never duplicating types across 'app/' and '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.
3

Engineers MUST NEVER import code from 'server/' into 'app/' or import Vue/client-specific composables from 'app/' into 'server/'.

Engineers MUST NEVER import code from 'server/' into 'app/' or import Vue/client-specific composables from 'app/' into '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.
4

Engineers MUST NEVER declare mutable state in module/top-level scope within Nitro event handlers ('server/api/**' or 'server/routes/**') because Node.js/Nitro processes persist module scope across concurrent HTTP requests.

Engineers MUST NEVER declare mutable state in module/top-level scope within Nitro event handlers ('server/api/**' or 'server/routes/**') because Node.js/Nitro processes persist module scope across concurrent 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.
5

Engineers MUST store request-scoped data exclusively on 'event.context' using Nitro middleware, or retrieve persisted server state via 'useStorage()'.

Engineers MUST store request-scoped data exclusively on 'event.context' using Nitro middleware, or retrieve persisted server state via 'useStorage()'.

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 NEVER use global 'ref()' or 'reactive()' declarations outside of component setup or 'useState()' inside composables, as this creates a shared singleton across all SSR sessions.

Engineers MUST NEVER use global 'ref()' or 'reactive()' declarations outside of component setup or 'useState()' inside composables, as this creates a shared singleton across all SSR sessions.

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.
7

Engineers MUST use 'useState(key, init)' for client-server SSR state hydration to guarantee isolated state per SSR request lifecycle.

Engineers MUST use 'useState(key, init)' for client-server SSR state hydration to guarantee isolated state per SSR request lifecycle.

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 Architecture & SSR State Isolation Standard critical for AI coding assistants?

Enforces strict boundary separation across Nuxt 4's app/, server/, and shared/ directories while eliminating cross-request state pollution in Nitro event handlers and Vue SSR composables. Mandates request-scoped context, unstorage/H3 event context over module-level singletons, and useState over global refs to prevent concurrent tenant data leakage. 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 Singletons and Illegal Directory 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