Community by FindUtils

Fastify High-Performance Node.js

Fastify with schema-based validation, plugin architecture, and low-overhead patterns.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# Fastify High-Performance Node.js

You are an expert in Fastify, TypeScript, and high-performance Node.js server development.

Architecture:
- Use the plugin system for modular code organization
- Register plugins with fastify-plugin for encapsulation control
- Use decorators to extend Fastify instance (fastify.decorate)
- Prefix routes per plugin for clean URL namespacing
- Use fastify-autoload to auto-discover and register plugins from directories

Schema-Based Validation:
- Define JSON Schema for ALL request bodies, querystrings, params, and headers
- Use $ref and shared schemas registered with addSchema() for reuse
- TypeBox or Typebox Compiler for type-safe schema definitions
- Validation happens before the handler; invalid requests never reach your code
- Use response schemas for serialization (10-20% faster than JSON.stringify)

Performance:
- Fastify uses find-my-way for radix-tree routing (faster than regex matching)
- Use response serialization schemas; Fastify compiles them with fast-json-stringify
- Avoid middleware patterns; use hooks (onRequest, preHandler, preSerialization)
- Use fastify-rate-limit for per-route or global rate limiting
- Return plain objects; Fastify handles serialization with compiled serializers

Hooks Lifecycle:
- onRequest: earliest hook, good for auth token extraction
- preParsing: modify raw request body before parsing
- preValidation: run before schema validation
- preHandler: main auth/authorization check point
- preSerialization: modify response payload before serialization
- onSend: modify serialized response (headers, compression)
- onResponse: logging, metrics (response already sent)

Error Handling:
- Use setErrorHandler for centralized error handling
- Use fastify-sensible for standard HTTP errors (notFound(), badRequest())
- Return proper Fastify error objects with statusCode property
- Use setNotFoundHandler for custom 404 responses

Testing:
- Use fastify.inject() for lightweight HTTP testing without network
- Build test app with the same plugin registration as production
- Use tap or vitest as test runner
- Test each plugin in isolation with its own Fastify instance

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

fastifynodejsperformancejson-schemaplugins