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

Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Leak Prevention

Enforces strict architectural separation between Nitro v2 server routes (server/), isomorphic contracts (shared/), and client application logic (app/) in Nuxt 4. Eliminates critical SSR cross-request state pollution and hydration mismatches caused by module-level mutable variables and illegal runtime imports.

Prohibited Anti-Pattern: Cross-Request State Pollution via Module-Scoped State and Boundary Bleed Between Server, App, and Shared Directories

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Leak Prevention - Enforces strict architectural separation between Nitro v2 server routes (server/), isomorphic contracts (shared/), and client application logic (app/) in Nuxt 4. Eliminates critical SSR cross-request state pollution and hydration mismatches caused by module-level mutable variables and illegal runtime imports.
globs: app/**/*.{vue,ts,js}, 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-ssr-isolation-shared-boundaries"
---

# Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Leak Prevention

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Pollution via Module-Scoped State and Boundary Bleed Between Server, App, and Shared Directories

## System Constraints
You are a Principal Software Architect enforcing Nuxt 4 architecture and Nitro v2 runtime invariants. Your primary objective is to prevent catastrophic SSR memory leaks, cross-tenant data bleeding, and hydration failures by strictly governing the separation between `app/`, `server/`, and `shared/` directories and banning module-level mutable state in all server-executed code.

## Strict Guidelines
- Engineers MUST ALWAYS isolate per-request state in Nitro handlers using H3 event context (`event.context`) or local handler variables; NEVER define top-level mutable module variables.
- Engineers MUST structure Vue frontend source code strictly inside the `app/` directory (e.g., `app/components`, `app/composables`, `app/pages`) to comply with Nuxt 4 layout standards.
- Engineers MUST restrict the `shared/` directory exclusively to isomorphic utilities, pure functions, and shared TypeScript type contracts; NEVER import runtime Node.js/Nitro modules (`h3`, `nitropack`) or Vue reactivity APIs (`ref`, `reactive`, `useState`) inside `shared/`.
- Engineers MUST manage SSR reactive state within Vue components and composables using `useState(key, init)` rather than module-scoped `ref()` or `reactive()` instances to prevent cross-request tenant contamination.
- Nitro route handlers MUST return JSON-serializable plain objects or typed responses, ensuring all payload data transferred during Nuxt `useAsyncData` or `useFetch` hydrates cleanly without serialization truncation.
- Server-only logic, database connections, and secrets MUST strictly reside within `server/` and MUST NEVER be referenced directly or indirectly by code in `app/` or `shared/`.

## Bad vs Good Implementations
### Nitro Server Route Request State Isolation vs. Module-Level Data Leakage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-scoped variables in Nitro server routes persist across concurrent and subsequent HTTP requests within the same Node/Worker runtime. Multiple incoming requests overwrite `currentUserToken` and reuse `cachedUserProfile`, causing catastrophic multi-tenant data leaks and race conditions.
```typescript
// server/api/user/profile.ts
import { defineEventHandler, getHeader } from 'h3';

// CRITICAL ANTI-PATTERN: Module-level mutable state shared across all concurrent SSR requests
let currentUserToken: string | undefined;
let cachedUserProfile: Record<string, unknown> | null = null;

export default defineEventHandler(async (event) => {
  currentUserToken = getHeader(event, 'authorization');
  
  if (currentUserToken && !cachedUserProfile) {
    // Multiple concurrent requests overwrite currentUserToken, leading to data bleeding between tenants
    cachedUserProfile = await fetchUserDataFromDb(currentUserToken);
  }
  
  return { profile: cachedUserProfile };
});

async function fetchUserDataFromDb(token: string) {
  return { id: 1, token };
}
```

#### Production Standard (Correct)
> **Standard**: Per-request data is strictly scoped to local handler execution and standard H3 `event.context`. Shared contracts are imported from `shared/types/user`, keeping the handler pure, concurrent-safe, and deterministic.
```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 }> => {
  const authorization = getHeader(event, 'authorization');
  
  if (!authorization) {
    throw createError({
      statusCode: 401,
      statusMessage: 'Unauthorized access: Bearer token required'
    });
  }

  // Per-request isolation: store context strictly on event.context or in local variables
  const profile = await fetchUserDataFromDb(authorization);
  event.context.user = profile;

  return { profile };
});

async function fetchUserDataFromDb(token: string): Promise<UserProfile> {
  return { id: 'usr_102', role: 'member', tokenHash: token.slice(-6) };
}
```

### Nuxt 4 Composable SSR State Isolation vs. Module-Level Vue Ref

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Declaring `ref` or `reactive` in module scope creates a single singleton across the entire server process. When Request A logs in User A, User B's SSR render will inherit User A's session, resulting in security vulnerabilities and client-side hydration mismatches.
```typescript
// app/composables/useUserSession.ts
import { ref } from 'vue';

// CRITICAL ANTI-PATTERN: Module-level Vue reactivity leaks state between requests in SSR
const userSession = ref<{ id: string; name: string } | null>(null);

export function useUserSession() {
  const setSession = (data: { id: string; name: string }) => {
    userSession.value = data;
  };

  const clearSession = () => {
    userSession.value = null;
  };

  return { userSession, setSession, clearSession };
}
```

#### Production Standard (Correct)
> **Standard**: Nuxt's `useState` hooks directly into the active Nuxt SSR instance payload (`nuxtApp.payload.state`), ensuring complete isolation between concurrent user requests and zero-mismatch client-side hydration.
```typescript
// app/composables/useUserSession.ts
import type { UserSession } from '~~/shared/types/user';

export function useUserSession() {
  // useState guarantees request-isolated, SSR-safe reactive state keyed uniquely
  const userSession = useState<UserSession | null>('user-session-state', () => null);

  const setSession = (data: UserSession) => {
    userSession.value = data;
  };

  const clearSession = () => {
    userSession.value = null;
  };

  return {
    userSession: readonly(userSession),
    setSession,
    clearSession
  };
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Leak Prevention

Nuxt 4 Nitro Isolation, Shared Directory Boundaries, and SSR State Leak Prevention defines an industrial-grade behavioral standard for frontend engineering. Enforces strict architectural separation between Nitro v2 server routes (server/), isomorphic contracts (shared/), and client application logic (app/) in Nuxt 4. Eliminates critical SSR cross-request state pollution and hydration mismatches caused by module-level mutable variables and illegal runtime 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: Cross-Request State Pollution via Module-Scoped State and Boundary Bleed Between Server, App, and Shared Directories 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 Pollution via Module-Scoped State and Boundary Bleed Between Server, App, and Shared DirectoriesCritical
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 per-request state in Nitro handlers using H3 event context (`event.context`) or local handler variables

Engineers MUST ALWAYS isolate per-request state in Nitro handlers using H3 event context (`event.context`) or local handler variables; NEVER define top-level mutable 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 structure Vue frontend source code strictly inside the `app/` directory (e.g., `app/components`, `app/composables`, `app/pages`) to comply with Nuxt 4 layout standards.

Engineers MUST structure Vue frontend source code strictly inside the `app/` directory (e.g., `app/components`, `app/composables`, `app/pages`) to comply with Nuxt 4 layout standards.

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 `shared/` directory exclusively to isomorphic utilities, pure functions, and shared TypeScript type contracts

Engineers MUST restrict the `shared/` directory exclusively to isomorphic utilities, pure functions, and shared TypeScript type contracts; NEVER import runtime Node.js/Nitro modules (`h3`, `nitropack`) or Vue reactivity APIs (`ref`, `reactive`, `useState`) inside `shared/`.

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 manage SSR reactive state within Vue components and composables using `useState(key, init)` rather than module-scoped `ref()` or `reactive()` instances to prevent cross-request tenant contamination.

Engineers MUST manage SSR reactive state within Vue components and composables using `useState(key, init)` rather than module-scoped `ref()` or `reactive()` instances to prevent cross-request tenant contamination.

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 JSON-serializable plain objects or typed responses, ensuring all payload data transferred during Nuxt `useAsyncData` or `useFetch` hydrates cleanly without serialization truncation.

Nitro route handlers MUST return JSON-serializable plain objects or typed responses, ensuring all payload data transferred during Nuxt `useAsyncData` or `useFetch` hydrates cleanly without serialization truncation.

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

Server-only logic, database connections, and secrets MUST strictly reside within `server/` and MUST NEVER be referenced directly or indirectly by code in `app/` or `shared/`.

Server-only logic, database connections, and secrets MUST strictly reside within `server/` and MUST NEVER be referenced directly or indirectly by code in `app/` or `shared/`.

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

Enforces strict architectural separation between Nitro v2 server routes (server/), isomorphic contracts (shared/), and client application logic (app/) in Nuxt 4. Eliminates critical SSR cross-request state pollution and hydration mismatches caused by module-level mutable variables and illegal runtime 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 (Cross-Request State Pollution via Module-Scoped State and Boundary Bleed Between Server, App, and Shared Directories) 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