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

Nuxt 4 Nitro Engine Isolation and Shared Directory Boundary Integrity

Enforces architectural isolation between the Nuxt 4 client layer (app/), server runtime engine (server/), and universally shared code (shared/). Guarantees the prevention of cross-request state contamination in Nitro v2 event handlers and prevents leakage of server-only secrets or Node.js primitives into isomorphic shared modules.

Prohibited Anti-Pattern: Module-Scope State Mutation in Nitro Handlers and Server-Boundary Leakage into Shared Layer

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Nuxt 4 Nitro Engine Isolation and Shared Directory Boundary Integrity - Enforces architectural isolation between the Nuxt 4 client layer (app/), server runtime engine (server/), and universally shared code (shared/). Guarantees the prevention of cross-request state contamination in Nitro v2 event handlers and prevents leakage of server-only secrets or Node.js primitives into isomorphic shared modules.
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/nuxt-4-nitro-shared-directory-isolation-guardrail"
---

# Nuxt 4 Nitro Engine Isolation and Shared Directory Boundary Integrity

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Module-Scope State Mutation in Nitro Handlers and Server-Boundary Leakage into Shared Layer

## System Constraints
You are a Principal Engineer enforcing Nuxt 4 Nitro Server Engine & Shared Directory invariants. Mandate strict boundary isolation between `app/`, `server/`, and `shared/` directories. Forbid module-level mutable state in Nitro handlers and SSR composables to eliminate cross-request state contamination. Prevent client-bundle poisoning by disallowing server runtime dependencies, node built-ins, and server secrets inside `shared/`.

## Strict Guidelines
- Engineers MUST ALWAYS isolate request state by using `event.context` in Nitro handlers and `useState()` in SSR-hydrated Vue composables; NEVER declare mutable module-level state outside handler execution scopes.
- Engineers MUST NOT import server-only primitives (`node:*`, database drivers, ORM clients, private runtime configs) into the `shared/` directory.
- Code inside `shared/` MUST be completely isomorphic, containing exclusively pure functions, TypeScript contracts, schemas (e.g., Zod), and deterministic utilities executable in both V8 and browser runtimes.
- Services running in Nitro event handlers MUST use `useNitroApp()`, Nitro plugins, or per-request event bindings instead of mutating global singleton instances.
- Components and Composables in `app/` MUST NEVER import directly from `server/`; communication must occur strictly via typed Nitro `$fetch` routes and isomorphic types located in `shared/types`.

## Bad vs Good Implementations
### Nitro Server Handler Request Isolation vs. Module-Level State Pollution

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Module-level variables persist across the Nitro server process lifecycle. When concurrent users invoke this endpoint, `cachedUserSession` is overwritten and shared across distinct requests, resulting in critical security leaks and data corruption.
```typescript
// server/api/user/profile.ts
import { defineEventHandler, getHeader } from 'h3';

// ANTI-PATTERN: Module-level shared state causes cross-request contamination in concurrent SSR requests
let cachedUserSession: { userId: string; role: string } | null = null;

export default defineEventHandler(async (event) => {
  const authHeader = getHeader(event, 'authorization');
  if (authHeader) {
    cachedUserSession = await verifySession(authHeader);
  }
  // Subsequent concurrent requests from different users will leak cachedUserSession
  return { user: cachedUserSession };
});

async function verifySession(token: string) {
  return { userId: '123', role: 'admin' };
}
```

#### Production Standard (Correct)
> **Standard**: State is strictly confined to `event.context` and local function execution frames. No mutable references exist in the module root, guaranteeing thread-safe, concurrent request processing without cross-tenant pollution.
```typescript
// server/api/user/profile.ts
import { defineEventHandler, getHeader, createError } from 'h3';
import type { UserProfileResponse } from '~~/shared/types/user';

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

  // Request-scoped assignment via event.context
  const session = await verifySession(authHeader);
  event.context.userSession = session;

  return {
    userId: event.context.userSession.userId,
    role: event.context.userSession.role
  };
});

async function verifySession(token: string) {
  return { userId: '123', role: 'admin' };
}
```

### Universal Shared Directory Contract vs. Server Secrets/Node Primitives Leakage

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Importing `node:crypto` and referencing `process.env.SERVER_HMAC_SECRET` in `shared/` causes client bundle bloat, build failures in non-Node environments (e.g., Cloudflare Workers), and leaks sensitive server keys to the client.
```typescript
// shared/utils/crypto.ts
import crypto from 'node:crypto'; // ANTI-PATTERN: Breaks browser compilation for app/

export function hashData(payload: string): string {
  // Leaking server-side runtime assumptions into client-consumed code
  const salt = process.env.SERVER_HMAC_SECRET || 'fallback-secret';
  return crypto.createHmac('sha256', salt).update(payload).digest('hex');
}
```

#### Production Standard (Correct)
> **Standard**: The shared layer maintains pure validation schemas and isomorphic functions with zero runtime secrets or platform-bound APIs. It safely compiles across client hydration bundles and Nitro server runtimes.
```typescript
// shared/validators/user.ts
import { z } from 'zod';

// Standard shared domain contract safe for both app/ and server/
export const UserProfileSchema = z.object({
  userId: z.string().uuid(),
  role: z.enum(['admin', 'member', 'guest']),
  email: z.string().email()
});

export type UserProfileResponse = z.infer<typeof UserProfileSchema>;

// Pure isomorphic utility
export function sanitizeUsername(input: string): string {
  return input.trim().toLowerCase().replace(/[^a-z0-9_-]/g, '');
}
```

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 Engine Isolation and Shared Directory Boundary Integrity

Nuxt 4 Nitro Engine Isolation and Shared Directory Boundary Integrity defines an industrial-grade behavioral standard for frontend engineering. Enforces architectural isolation between the Nuxt 4 client layer (app/), server runtime engine (server/), and universally shared code (shared/). Guarantees the prevention of cross-request state contamination in Nitro v2 event handlers and prevents leakage of server-only secrets or Node.js primitives into isomorphic shared modules. 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: Module-Scope State Mutation in Nitro Handlers and Server-Boundary Leakage into Shared Layer 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 DriftModule-Scope State Mutation in Nitro Handlers and Server-Boundary Leakage into Shared LayerCritical
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 request state by using `event.context` in Nitro handlers and `useState()` in SSR-hydrated Vue composables

Engineers MUST ALWAYS isolate request state by using `event.context` in Nitro handlers and `useState()` in SSR-hydrated Vue composables; NEVER declare mutable module-level state outside handler execution scopes.

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 primitives (`node

Engineers MUST NOT import server-only primitives (`node:*`, database drivers, ORM clients, private runtime configs) into the `shared/` 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.
3

Code inside `shared/` MUST be completely isomorphic, containing exclusively pure functions, TypeScript contracts, schemas (e.g., Zod), and deterministic utilities executable in both V8 and browser runtimes.

Code inside `shared/` MUST be completely isomorphic, containing exclusively pure functions, TypeScript contracts, schemas (e.g., Zod), and deterministic utilities executable in both V8 and browser runtimes.

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 running in Nitro event handlers MUST use `useNitroApp()`, Nitro plugins, or per-request event bindings instead of mutating global singleton instances.

Services running in Nitro event handlers MUST use `useNitroApp()`, Nitro plugins, or per-request event bindings instead of mutating global singleton instances.

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 and Composables in `app/` MUST NEVER import directly from `server/`

Components and Composables in `app/` MUST NEVER import directly from `server/`; communication must occur strictly via typed Nitro `$fetch` routes and isomorphic types located in `shared/types`.

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 Boundary Integrity critical for AI coding assistants?

Enforces architectural isolation between the Nuxt 4 client layer (app/), server runtime engine (server/), and universally shared code (shared/). Guarantees the prevention of cross-request state contamination in Nitro v2 event handlers and prevents leakage of server-only secrets or Node.js primitives into isomorphic shared modules. 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 (Module-Scope State Mutation in Nitro Handlers and Server-Boundary Leakage into Shared Layer) 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