Fastify (TypeScript) - Production Backend Framework
Overview
Fastify is a high-performance Node.js web framework built around JSON schema validation, encapsulated plugins, and great developer ergonomics. In TypeScript, pair Fastify with a type provider (Zod or TypeBox) to keep runtime validation and static types aligned.
Quick Start
Minimal server
✅ Correct: basic server with typed response
❌ Wrong: start server without awaiting listen
Schema Validation + Type Providers
Fastify validates requests/responses via JSON schema. Use a type provider to avoid duplicating types.
Zod provider (recommended for full-stack TypeScript)
✅ Correct: Zod schema drives validation + types
TypeBox provider (recommended for OpenAPI + performance)
✅ Correct: TypeBox schema
Plugin Architecture (Encapsulation)
Use plugins to keep concerns isolated and testable (auth, db, routes).
✅ Correct: route plugin
✅ Correct: register with a prefix
Error Handling
Centralize unexpected failures and return stable error shapes.
✅ Correct: setErrorHandler
Security Hardening (Baseline)
Add standard security plugins and enforce payload limits.
✅ Correct: Helmet + CORS + rate limiting
Graceful Shutdown
Close HTTP server and downstream clients (DB, queues) on SIGINT/SIGTERM.
✅ Correct: close on signals
Testing (Fastify inject)
Test routes in-memory without binding ports.
✅ Correct: inject request
Decision Trees
Fastify vs Express
- Prefer Fastify for schema-based validation, predictable plugins, and high throughput.
- Prefer Express for minimal middleware and maximal ecosystem familiarity.
Zod vs TypeBox
- Prefer Zod for app codebases that already standardize on Zod (forms, tRPC, shared types).
- Prefer TypeBox for OpenAPI generation and performance-critical validation.
Anti-Patterns
- Skip request validation; validate at boundaries with schemas.
- Register everything in
main.ts; isolate routes and dependencies into plugins. - Return raw error objects; return stable error shapes and log the details.
Resources
- Fastify: https://www.fastify.io/
- fastify-type-provider-zod: https://github.com/turkerdev/fastify-type-provider-zod
- @fastify/type-provider-typebox: https://github.com/fastify/fastify-type-provider-typebox


