This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: fastify-5-schema-encapsulation-guardrails

Fastify 5 Encapsulation Boundaries, Custom Compilers, and Route Scopes

Enforces boundary encapsulation in Fastify 5 to prevent schema contamination and hook leakage across plugin hierarchies. Mandates isolated route contexts for hooks and serializers while preserving safe centralized schema resolution via fast-json-stringify and Ajv.

Prohibited Anti-Pattern: Leaking Route-Level Hooks and Schema Collisions Across Sibling Contexts via Misused fastify-plugin Hoisting

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Fastify 5 Encapsulation Boundaries, Custom Compilers, and Route Scopes - Enforces boundary encapsulation in Fastify 5 to prevent schema contamination and hook leakage across plugin hierarchies. Mandates isolated route contexts for hooks and serializers while preserving safe centralized schema resolution via fast-json-stringify and Ajv.
globs: src/routes/**/*.ts, src/plugins/**/*.ts, src/app.ts, src/server.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/fastify-5-schema-encapsulation-guardrails"
---

# Fastify 5 Encapsulation Boundaries, Custom Compilers, and Route Scopes

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Leaking Route-Level Hooks and Schema Collisions Across Sibling Contexts via Misused fastify-plugin Hoisting

## System Constraints
You are a Principal Backend Architect enforcing Fastify 5 encapsulation and validation invariants. Fastify builds an encapsulated directed acyclic graph (DAG) of plugin contexts. You must prevent hook leakage, decorator pollution, and serializer compiler conflicts by strictly separating hoisted infrastructure plugins from encapsulated route trees.

## Strict Guidelines
- Engineers MUST ALWAYS declare route collections as standard async functions without wrapping them in fastify-plugin (fp), ensuring hooks (e.g., preHandler, onRequest) remain strictly scoped to that route branch.
- Engineers MUST ONLY use fastify-plugin (fp) for cross-cutting global utilities, singleton clients (e.g., Prisma, Redis), and root-level decorators.
- Engineers MUST register shared entity schemas using fastify.addSchema() at the root instance or a deterministic parent scope before registering consumer child plugins to prevent unresolvable $ref errors.
- Engineers MUST declare explicit response schemas for all 2xx status codes using fast-json-stringify or TypeBox to guarantee serialization performance and prevent prototype or secret property leakage.
- Services MUST NOT mutate fastify.setValidatorCompiler or fastify.setSerializerCompiler inside leaf route plugins unless the intent is scoped exclusively to that branch.
- Route hooks MUST be registered via fastify.addHook() inside the encapsulated plugin context or attached directly to the RouteOptions definition, never via an fp-wrapped wrapper.

## Bad vs Good Implementations
### Encapsulated Sub-Router with Route-Scoped Hook vs. Leaked fastify-plugin

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Wrapping a route file in fastify-plugin breaks Fastify's encapsulation tree. The onRequest authentication hook is hoisted to the root or parent context, inadvertently protecting unrelated public routes (or crashing sibling plugins) and causing shared schema ID collisions.
```typescript
import fp from 'fastify-plugin';
import { FastifyInstance, FastifyPluginAsync } from 'fastify';

// ANTI-PATTERN: Wrapping route modules with fastify-plugin (fp).
// This breaks encapsulation, leaking the auth hook and schema definitions
// to the parent context and all sibling route plugins!
export const userRoutes: FastifyPluginAsync = fp(async (fastify: FastifyInstance) => {
  fastify.addHook('onRequest', async (request, reply) => {
    if (!request.headers.authorization) {
      reply.code(401).send({ error: 'Unauthorized' });
    }
  });

  // Leaked schema definition can collide with sibling modules
  fastify.addSchema({
    $id: 'User',
    type: 'object',
    properties: { id: { type: 'string' }, name: { type: 'string' } }
  });

  fastify.get('/users/me', async (request) => {
    return { id: 'usr_1', name: 'Alice' };
  });
});
```

#### Production Standard (Correct)
> **Standard**: By exporting a pure asynchronous plugin function without fastify-plugin, Fastify creates an isolated child context. The onRequest hook applies solely to routes registered within this plugin and its descendants, preventing hook leakage and schema collision across siblings.
```typescript
import { FastifyInstance, FastifyPluginAsync } from 'fastify';
import { Type, Static } from '@sinclair/typebox';

const UserResponseSchema = Type.Object({
  id: Type.String(),
  name: Type.String()
});
type UserResponse = Static<typeof UserResponseSchema>;

// CORRECT: Pure async plugin creates a child encapsulation context.
// Hooks and local schemas are completely isolated from siblings.
export const userRoutes: FastifyPluginAsync = async (fastify: FastifyInstance) => {
  // Hook is strictly bound to this encapsulated /users branch
  fastify.addHook('onRequest', async (request, reply) => {
    if (!request.headers.authorization) {
      reply.code(401).send({ error: 'Unauthorized' });
    }
  });

  fastify.get<{ Reply: UserResponse }>(
    '/me',
    {
      schema: {
        response: {
          200: UserResponseSchema
        }
      }
    },
    async (request) => {
      return { id: 'usr_1', name: 'Alice' };
    }
  );
};
```

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: Fastify 5 Encapsulation Boundaries, Custom Compilers, and Route Scopes

Fastify 5 Encapsulation Boundaries, Custom Compilers, and Route Scopes defines an industrial-grade behavioral standard for backend engineering. Enforces boundary encapsulation in Fastify 5 to prevent schema contamination and hook leakage across plugin hierarchies. Mandates isolated route contexts for hooks and serializers while preserving safe centralized schema resolution via fast-json-stringify and Ajv. 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: Leaking Route-Level Hooks and Schema Collisions Across Sibling Contexts via Misused fastify-plugin Hoisting 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 DriftLeaking Route-Level Hooks and Schema Collisions Across Sibling Contexts via Misused fastify-plugin HoistingCritical
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 declare route collections as standard async functions without wrapping them in fastify-plugin (fp), ensuring hooks (e.g., preHandler, onRequest) remain strictly scoped to that route branch.

Engineers MUST ALWAYS declare route collections as standard async functions without wrapping them in fastify-plugin (fp), ensuring hooks (e.g., preHandler, onRequest) remain strictly scoped to that route branch.

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 ONLY use fastify-plugin (fp) for cross-cutting global utilities, singleton clients (e.g., Prisma, Redis), and root-level decorators.

Engineers MUST ONLY use fastify-plugin (fp) for cross-cutting global utilities, singleton clients (e.g., Prisma, Redis), and root-level decorators.

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 register shared entity schemas using fastify.addSchema() at the root instance or a deterministic parent scope before registering consumer child plugins to prevent unresolvable $ref errors.

Engineers MUST register shared entity schemas using fastify.addSchema() at the root instance or a deterministic parent scope before registering consumer child plugins to prevent unresolvable $ref errors.

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 declare explicit response schemas for all 2xx status codes using fast-json-stringify or TypeBox to guarantee serialization performance and prevent prototype or secret property leakage.

Engineers MUST declare explicit response schemas for all 2xx status codes using fast-json-stringify or TypeBox to guarantee serialization performance and prevent prototype or secret property leakage.

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

Services MUST NOT mutate fastify.setValidatorCompiler or fastify.setSerializerCompiler inside leaf route plugins unless the intent is scoped exclusively to that branch.

Services MUST NOT mutate fastify.setValidatorCompiler or fastify.setSerializerCompiler inside leaf route plugins unless the intent is scoped exclusively to that branch.

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

Route hooks MUST be registered via fastify.addHook() inside the encapsulated plugin context or attached directly to the RouteOptions definition, never via an fp-wrapped wrapper.

Route hooks MUST be registered via fastify.addHook() inside the encapsulated plugin context or attached directly to the RouteOptions definition, never via an fp-wrapped wrapper.

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 Fastify 5 Encapsulation Boundaries, Custom Compilers, and Route Scopes critical for AI coding assistants?

Enforces boundary encapsulation in Fastify 5 to prevent schema contamination and hook leakage across plugin hierarchies. Mandates isolated route contexts for hooks and serializers while preserving safe centralized schema resolution via fast-json-stringify and Ajv. 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 (Leaking Route-Level Hooks and Schema Collisions Across Sibling Contexts via Misused fastify-plugin Hoisting) 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.

1 Rule in Stack

Fastify