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

Nuxt 4 Directory Restructuring & Nitro Isolated State Guardrail

Enforces strict boundary isolation across Nuxt 4's app/, server/, and shared/ directories, preventing cross-request state leakage in Nitro v2 server handlers. Mandates that universal utilities residing in shared/ remain side-effect free and client-safe, while ensuring SSR state hydration leverages unpolluted, request-scoped contexts.

Prohibited Anti-Pattern: Global Mutable State Pollution in Nitro Handlers and Leaking Server Context via shared/

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Directory Restructuring & Nitro Isolated State Guardrail - Enforces strict boundary isolation across Nuxt 4's app/, server/, and shared/ directories, preventing cross-request state leakage in Nitro v2 server handlers. Mandates that universal utilities residing in shared/ remain side-effect free and client-safe, while ensuring SSR state hydration leverages unpolluted, request-scoped contexts.
globs: app/**/*.{vue,ts,js}, 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-hydration-guardrail"
---

# Nuxt 4 Directory Restructuring & Nitro Isolated State Guardrail

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Global Mutable State Pollution in Nitro Handlers and Leaking Server Context via shared/

## System Constraints
You are a Principal Nuxt Architect enforcing strict directory boundaries and state isolation in Nuxt 4 with Nitro v2. Mandate the correct usage of app/, server/, and shared/ directories. Prohibit module-level mutable singletons in server handlers to prevent multi-tenant cross-request state leakage during SSR. Ensure that code imported from shared/ never contains server secrets, Node-only APIs, or mutable global runtime state, and enforce proper hydration lifecycle safety.

## Strict Guidelines
- Engineers MUST ALWAYS isolate SSR state per request using `useState()` or Nitro `event.context`, NEVER using module-scoped mutable variables or module singletons.
- Engineers MUST NOT import server-only modules, database drivers, or private runtime environment secrets into code located under `shared/` or `app/`.
- Code placed in `shared/` MUST remain pure, isomorphic, and completely side-effect free, containing only common types, pure deterministic validators, or mathematical transforms.
- Services in `server/api/` or `server/routes/` MUST instantiate stateful instances per event execution or inject them strictly through `event.context`.
- Components NEVER use global `ref()` or `reactive()` outside of `setup()` or composable scopes; all shared component SSR states MUST be registered via `useState(key, init)` to ensure serialized hydration continuity.

## Bad vs Good Implementations
### Nitro Server Route State Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-scoped mutable variables in Nitro handlers survive across distinct incoming HTTP requests in persistent server environments (Node/Bun/Worker long-lived instances), resulting in critical multi-tenant data leaks.
```typescript
// server/api/user.ts
// ANTI-PATTERN: Module-level mutable state leaks across concurrent tenant requests
let cachedUserSession: { userId: string } | null = null;

export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'authorization');
  if (token) {
    cachedUserSession = await verifyAndResolveUser(token);
  }
  // If another request hits the server without a token, it will access the previous user's session!
  return { user: cachedUserSession };
});
```

#### Production Standard (Correct)
> **Standard**: Attaching request-scoped data to `event.context` or computing within the handler closure guarantees total isolation between concurrent requests without memory or security leaks.
```typescript
// server/api/user.ts
// PRODUCTION-GRADE: Request-scoped isolation via event.context
export default defineEventHandler(async (event) => {
  const token = getHeader(event, 'authorization');
  
  // Maintain request isolation
  const session = token ? await verifyAndResolveUser(token) : null;
  event.context.userSession = session;

  return { user: event.context.userSession };
});
```

### Nuxt 4 shared/ Directory Boundary Protection

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The `shared/` directory is automatically exposed and bundled for both `app/` (client-side) and `server/`. Importing Node-specific modules or referencing unexposed environment secrets breaks client builds or exposes secrets.
```typescript
// shared/utils/auth.ts
// ANTI-PATTERN: Leaking Nitro server-only crypto dependencies and private environment config into shared/
import crypto from 'node:crypto';

export const generateHash = (data: string): string => {
  const secret = process.env.API_SECRET_KEY || 'default'; // Leaks in client bundle or breaks in browser
  return crypto.createHmac('sha256', secret).update(data).digest('hex');
};
```

#### Production Standard (Correct)
> **Standard**: Code inside `shared/` is strictly isomorphic, runtime-agnostic, and contains no server credentials, ensuring deterministic execution in both client hydration and server-side rendering.
```typescript
// shared/utils/validation.ts
// PRODUCTION-GRADE: Isomorphic, pure schema/validator safe for both app/ and server/
export interface UserPayload {
  email: string;
  tenantId: string;
}

export const isValidEmail = (email: string): boolean => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(email);
};
```

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 Directory Restructuring & Nitro Isolated State Guardrail

Nuxt 4 Directory Restructuring & Nitro Isolated State Guardrail defines an industrial-grade behavioral standard for frontend engineering. Enforces strict boundary isolation across Nuxt 4's app/, server/, and shared/ directories, preventing cross-request state leakage in Nitro v2 server handlers. Mandates that universal utilities residing in shared/ remain side-effect free and client-safe, while ensuring SSR state hydration leverages unpolluted, request-scoped contexts. 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 Mutable State Pollution in Nitro Handlers and Leaking Server Context via shared/ 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 Mutable State Pollution in Nitro Handlers and Leaking Server Context via shared/Critical
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 SSR state per request using `useState()` or Nitro `event.context`, NEVER using module-scoped mutable variables or module singletons.

Engineers MUST ALWAYS isolate SSR state per request using `useState()` or Nitro `event.context`, NEVER using module-scoped mutable variables or module singletons.

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 server-only modules, database drivers, or private runtime environment secrets into code located under `shared/` or `app/`.

Engineers MUST NOT import server-only modules, database drivers, or private runtime environment secrets into code located under `shared/` or `app/`.

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

Code placed in `shared/` MUST remain pure, isomorphic, and completely side-effect free, containing only common types, pure deterministic validators, or mathematical transforms.

Code placed in `shared/` MUST remain pure, isomorphic, and completely side-effect free, containing only common types, pure deterministic validators, or mathematical transforms.

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

Services in `server/api/` or `server/routes/` MUST instantiate stateful instances per event execution or inject them strictly through `event.context`.

Services in `server/api/` or `server/routes/` MUST instantiate stateful instances per event execution or inject them strictly through `event.context`.

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

Components NEVER use global `ref()` or `reactive()` outside of `setup()` or composable scopes

Components NEVER use global `ref()` or `reactive()` outside of `setup()` or composable scopes; all shared component SSR states MUST be registered via `useState(key, init)` to ensure serialized hydration continuity.

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 Directory Restructuring & Nitro Isolated State Guardrail critical for AI coding assistants?

Enforces strict boundary isolation across Nuxt 4's app/, server/, and shared/ directories, preventing cross-request state leakage in Nitro v2 server handlers. Mandates that universal utilities residing in shared/ remain side-effect free and client-safe, while ensuring SSR state hydration leverages unpolluted, request-scoped contexts. 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 Mutable State Pollution in Nitro Handlers and Leaking Server Context via shared/) 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