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

Nuxt 4 Nitro Engine Isolation and Shared Directory SSR Invariants

Enforces strict execution-context isolation between Nuxt 4 app/, server/, and shared/ directories. Prohibits top-level mutable state in Nitro handlers to prevent cross-request tenant bleed and guarantees safe SSR hydration serialization.

Prohibited Anti-Pattern: Cross-Request State Pollution via Top-Level Nitro Variables and Leaky Shared Directory Contexts

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Engine Isolation and Shared Directory SSR Invariants - Enforces strict execution-context isolation between Nuxt 4 app/, server/, and shared/ directories. Prohibits top-level mutable state in Nitro handlers to prevent cross-request tenant bleed and guarantees safe SSR hydration serialization.
globs: app/**/*.{ts,vue}, server/**/*.{ts,js}, shared/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nuxt4-nitro-shared-ssr-boundary-guardrail"
---

# Nuxt 4 Nitro Engine Isolation and Shared Directory SSR Invariants

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Cross-Request State Pollution via Top-Level Nitro Variables and Leaky Shared Directory Contexts

## System Constraints
You are a Principal Software Architect enforcing strict boundaries and execution-context isolation in Nuxt 4 and Nitro v2 applications. You must reject any code containing top-level mutable variables in Nitro server routes, prevent client/server cross-imports across app/ and server/, and ensure code in shared/ is strictly isomorphic and pure.

## Strict Guidelines
- Engineers MUST NEVER declare mutable state at the module/top level of Nitro server handlers (`server/api/*`, `server/routes/*`, `server/middleware/*`), as Node/worker processes are long-lived and will leak state across different user requests.
- Engineers MUST attach request-scoped state exclusively to H3 `event.context` within Nitro middleware and retrieve it safely in downstream event handlers.
- Engineers MUST ensure code located in `shared/` is strictly isomorphic: it MUST NOT import Node-only packages (`fs`, `crypto`, `child_process`), database clients, or DOM-dependent browser globals (`window`, `document`).
- Engineers MUST NEVER import client-side Vue reactivity APIs (`ref`, `reactive`, `computed`, `useState`) or Nuxt composables inside `server/` routes.
- Engineers MUST NEVER import Nitro utilities (`eventHandler`, `readBody`, `getQuery`, `setCookie`) inside `app/` Vue components or composables.
- Components and composables MUST use Nuxt 4's `useState()` with deterministic, globally unique string keys to hydrate data from SSR to CSR; bare global module-level `ref` declarations in SSR contexts are strictly prohibited.
- Nitro event handlers MUST return JSON-serializable plain data structures matching contracts exported from `shared/`, never class instances with prototype chains or circular references.

## Bad vs Good Implementations
### Prevent Cross-Request State Bleed in Nitro Event Handlers

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: In Nitro's long-lived Node.js or edge worker runtime, module-level variables are shared across all incoming requests. Mutating 'currentUserSession' causes critical multi-tenant data leaks and race conditions between unrelated client sessions.
```typescript
// server/api/user/session.ts - ANTI-PATTERN: Module-scoped state persists across HTTP requests
let currentUserSession: { userId: string; role: string } | null = null;

export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'authorization');
  if (token) {
    // DANGEROUS: Concurrent requests overwrite or read other users' session state
    currentUserSession = await verifyUserSession(token);
  }
  return { session: currentUserSession };
});
```

#### Production Standard (Correct)
> **Standard**: Assigning request-scoped data to `event.context` ensures complete isolation per HTTP transaction. No memory leaks or cross-tenant contamination can occur across concurrent SSR requests.
```typescript
// server/api/user/session.ts - PRODUCTION INVARIANT: Request-scoped isolation via event.context
import { defineEventHandler, getHeader, createError } from 'h3';
import type { UserSessionDTO } from '~~/shared/types/auth';

declare module 'h3' {
  interface H3EventContext {
    session?: UserSessionDTO;
  }
}

export default defineEventHandler(async (event): Promise<{ session: UserSessionDTO }> => {
  const token = getHeader(event, 'authorization');
  if (!token) {
    throw createError({ statusCode: 401, statusMessage: 'Unauthorized' });
  }

  // State is bounded exclusively to the lifecycle of this single request
  const session = await verifyUserSession(token);
  event.context.session = session;

  return { session: event.context.session };
});
```

### Nuxt 4 Shared Directory Isomorphism and Safe SSR Hydration

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Code in Nuxt 4's `shared/` directory is compiled for both Nitro (server) and App (client/SSR). Referencing browser globals like `window` causes unhandled ReferenceErrors during SSR compilation or Nitro execution.
```typescript
// shared/utils/formatter.ts - ANTI-PATTERN: Client-side DOM assumptions in shared/
export function formatCurrency(amount: number): string {
  // Leaks browser dependency: breaks during SSR if window is evaluated
  const userLocale = window.navigator.language || 'en-US';
  return new Intl.NumberFormat(userLocale, { style: 'currency', currency: 'USD' }).format(amount);
}
```

#### Production Standard (Correct)
> **Standard**: Shared utilities must be purely deterministic and accept all contextual information (such as locale) as parameters. This allows safe, dual-environment execution across both Nitro routes and Vue components without hydration mismatch.
```typescript
// shared/utils/formatter.ts - PRODUCTION INVARIANT: Deterministic, Isomorphic Contract
import { z } from 'zod';

export const CurrencyPayloadSchema = z.object({
  amount: z.number().finite(),
  locale: z.string().default('en-US'),
  currency: z.string().length(3).default('USD')
});

export type CurrencyPayload = z.infer<typeof CurrencyPayloadSchema>;

export function formatCurrency(payload: CurrencyPayload): string {
  const validated = CurrencyPayloadSchema.parse(payload);
  return new Intl.NumberFormat(validated.locale, {
    style: 'currency',
    currency: validated.currency
  }).format(validated.amount);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Nuxt 4 Nitro Engine Isolation and Shared Directory SSR Invariants

Nuxt 4 Nitro Engine Isolation and Shared Directory SSR Invariants defines an industrial-grade behavioral standard for frontend engineering. Enforces strict execution-context isolation between Nuxt 4 app/, server/, and shared/ directories. Prohibits top-level mutable state in Nitro handlers to prevent cross-request tenant bleed and guarantees safe SSR hydration serialization. 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 Top-Level Nitro Variables and Leaky Shared Directory Contexts 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 Top-Level Nitro Variables and Leaky Shared Directory ContextsCritical
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 at the module/top level of Nitro server handlers (`server/api/*`, `server/routes/*`, `server/middleware/*`), as Node/worker processes are long-lived and will leak state across different user requests.

Engineers MUST NEVER declare mutable state at the module/top level of Nitro server handlers (`server/api/*`, `server/routes/*`, `server/middleware/*`), as Node/worker processes are long-lived and will leak state across different user 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 attach request-scoped state exclusively to H3 `event.context` within Nitro middleware and retrieve it safely in downstream event handlers.

Engineers MUST attach request-scoped state exclusively to H3 `event.context` within Nitro middleware and retrieve it safely in downstream event handlers.

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 ensure code located in `shared/` is strictly isomorphic

Engineers MUST ensure code located in `shared/` is strictly isomorphic: it MUST NOT import Node-only packages (`fs`, `crypto`, `child_process`), database clients, or DOM-dependent browser globals (`window`, `document`).

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 import client-side Vue reactivity APIs (`ref`, `reactive`, `computed`, `useState`) or Nuxt composables inside `server/` routes.

Engineers MUST NEVER import client-side Vue reactivity APIs (`ref`, `reactive`, `computed`, `useState`) or Nuxt composables inside `server/` 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.
5

Engineers MUST NEVER import Nitro utilities (`eventHandler`, `readBody`, `getQuery`, `setCookie`) inside `app/` Vue components or composables.

Engineers MUST NEVER import Nitro utilities (`eventHandler`, `readBody`, `getQuery`, `setCookie`) inside `app/` Vue components or composables.

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 and composables MUST use Nuxt 4's `useState()` with deterministic, globally unique string keys to hydrate data from SSR to CSR

Components and composables MUST use Nuxt 4's `useState()` with deterministic, globally unique string keys to hydrate data from SSR to CSR; bare global module-level `ref` declarations in SSR contexts are strictly prohibited.

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

Nitro event handlers MUST return JSON-serializable plain data structures matching contracts exported from `shared/`, never class instances with prototype chains or circular references.

Nitro event handlers MUST return JSON-serializable plain data structures matching contracts exported from `shared/`, never class instances with prototype chains or circular references.

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

Enforces strict execution-context isolation between Nuxt 4 app/, server/, and shared/ directories. Prohibits top-level mutable state in Nitro handlers to prevent cross-request tenant bleed and guarantees safe SSR hydration serialization. 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 Top-Level Nitro Variables and Leaky Shared Directory Contexts) 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