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

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

Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ utilities. Prevents cross-request state pollution, runtime leakage of server-only primitives into client bundles, and un-isolated SSR state hydration bugs.

Prohibited Anti-Pattern: Global Module-Level State in Nitro Handlers and Cross-Polluting Shared Directory Imports

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Server Engine, Shared Directory, and SSR State Isolation - Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ utilities. Prevents cross-request state pollution, runtime leakage of server-only primitives into client bundles, and un-isolated SSR state hydration bugs.
globs: app/**/*.{ts,vue}, server/**/*.{ts,js}, shared/**/*.{ts,js}, nuxt.config.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nuxt4-nitro-shared-ssr-guardrails"
---

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

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Global Module-Level State in Nitro Handlers and Cross-Polluting Shared Directory Imports

## System Constraints
You are a Principal Software Architect enforcing production invariants for Nuxt 4, Nitro v2/v3 server runtimes, and SSR hydration. Mandate absolute memory isolation across incoming SSR requests, ensure proper usage of the shared/ directory without leaking server context or client Vue reactivity, and prevent hydration mismatch or security leaks caused by shared singletons.

## Strict Guidelines
- Engineers MUST NEVER declare global or module-scoped state variables within Nitro server handlers or composables that mutate per request.
- Engineers MUST ALWAYS isolate SSR state per request using `useState()` in the Nuxt app context and event context (`event.context`) in Nitro handlers.
- Engineers MUST ensure code placed in the `shared/` directory contains only isomorphic, pure logic, validation schemas (e.g., Zod), and shared types, with ZERO dependencies on Vue reactivity (`ref`, `reactive`) or Node/Nitro server primitives (`H3Event`, `fs`, `useStorage`).
- Engineers MUST NOT import server-only packages, Nitro utilities, or private server runtime configurations into `app/` or isomorphic `shared/` files.
- Engineers MUST explicitly utilize `defineEventHandler` in Nitro routes and avoid raw Node HTTP request mutations.
- Components NEVER store sensitive server payloads or non-serializable objects in `useState()` or `useAsyncData()` payloads destined for SSR hydration transfer.

## Bad vs Good Implementations
### Cross-Request Memory Leak in Nitro Handler vs. Event-Isolated Context

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-scoped variables in Nitro server routes persist across concurrent and subsequent HTTP requests on warm server instances, leaking sensitive session state across distinct users.
```typescript
// server/api/user-session.ts
import { defineEventHandler } from 'h3';

// CRITICAL BUG: Module-scoped state shared across all concurrent requests in the Nitro Node/V8 runtime!
let currentUser: { id: string; role: string } | null = null;

export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'authorization');
  if (token) {
    currentUser = await verifyToken(token);
  }
  // Subsequent requests will leak the previous user's credentials
  return { user: currentUser };
});
```

#### Production Standard (Correct)
> **Standard**: State is securely constrained to the current execution frame and H3Event context, strictly preventing cross-request pollution.
```typescript
// server/api/user-session.ts
import { defineEventHandler, getHeader, createError } from 'h3';

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

  // SAFE: Scoped directly to the individual H3Event context
  const user = await verifyToken(token);
  event.context.user = user;

  return { user };
});
```

### Contaminated Shared Directory Logic vs. Isomorphic Pure Utility

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Importing Vue reactivity or Nitro-specific `#imports` into the `shared/` directory breaks isomorphism, breaks bundling on the opposite side, and introduces reactivity hazards outside Vue scope.
```typescript
// shared/utils/auth.ts
import { ref } from 'vue'; // VIOLATION: Injecting Vue reactivity into shared engine logic
import { useStorage } from '#imports'; // VIOLATION: Nitro server-only virtual import

export const authState = ref(null);

export async function getCachedToken(key: string) {
  const storage = useStorage('redis');
  return await storage.getItem(key);
}
```

#### Production Standard (Correct)
> **Standard**: The shared utility remains pure, containing only serializable types and isomorphic validations usable seamlessly by both `app/` Vue components and `server/` Nitro routes.
```typescript
// shared/utils/auth.ts
import { z } from 'zod';

// SAFE: Isomorphic schema validation compatible with app/, server/, and edge runtimes
export const UserSchema = z.object({
  id: z.string().uuid(),
  email: z.string().email(),
  role: z.enum(['admin', 'member', 'guest'])
});

export type User = z.infer<typeof UserSchema>;

export function isValidUser(data: unknown): data is User {
  return UserSchema.safeParse(data).success;
}
```

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

Nuxt 4 Nitro Server Engine, Shared Directory, and SSR State Isolation defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ utilities. Prevents cross-request state pollution, runtime leakage of server-only primitives into client bundles, and un-isolated SSR state hydration bugs. 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: Global Module-Level State in Nitro Handlers and Cross-Polluting Shared 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 DriftGlobal Module-Level State in Nitro Handlers and Cross-Polluting Shared 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 NEVER declare global or module-scoped state variables within Nitro server handlers or composables that mutate per request.

Engineers MUST NEVER declare global or module-scoped state variables within Nitro server handlers or composables that mutate 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.
2

Engineers MUST ALWAYS isolate SSR state per request using `useState()` in the Nuxt app context and event context (`event.context`) in Nitro handlers.

Engineers MUST ALWAYS isolate SSR state per request using `useState()` in the Nuxt app context and event context (`event.context`) in Nitro 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 placed in the `shared/` directory contains only isomorphic, pure logic, validation schemas (e.g., Zod), and shared types, with ZERO dependencies on Vue reactivity (`ref`, `reactive`) or Node/Nitro server primitives (`H3Event`, `fs`, `useStorage`).

Engineers MUST ensure code placed in the `shared/` directory contains only isomorphic, pure logic, validation schemas (e.g., Zod), and shared types, with ZERO dependencies on Vue reactivity (`ref`, `reactive`) or Node/Nitro server primitives (`H3Event`, `fs`, `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.
4

Engineers MUST NOT import server-only packages, Nitro utilities, or private server runtime configurations into `app/` or isomorphic `shared/` files.

Engineers MUST NOT import server-only packages, Nitro utilities, or private server runtime configurations into `app/` or isomorphic `shared/` files.

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 explicitly utilize `defineEventHandler` in Nitro routes and avoid raw Node HTTP request mutations.

Engineers MUST explicitly utilize `defineEventHandler` in Nitro routes and avoid raw Node HTTP request mutations.

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 store sensitive server payloads or non-serializable objects in `useState()` or `useAsyncData()` payloads destined for SSR hydration transfer.

Components NEVER store sensitive server payloads or non-serializable objects in `useState()` or `useAsyncData()` payloads destined for SSR hydration transfer.

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

Enforces strict boundary separation between Nuxt 4's app/ directory, Nitro server runtime, and shared/ utilities. Prevents cross-request state pollution, runtime leakage of server-only primitives into client bundles, and un-isolated SSR state hydration bugs. 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 (Global Module-Level State in Nitro Handlers and Cross-Polluting Shared 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