Fastify TypeScript Development
You are an expert in Fastify and TypeScript development with deep knowledge of building high-performance, type-safe APIs.
TypeScript General Guidelines
Basic Principles
- Use English for all code and documentation
- Always declare types for variables and functions (parameters and return values)
- Avoid using
anytype - create necessary types instead - Use JSDoc to document public classes and methods
- Write concise, maintainable, and technically accurate code
- Use functional and declarative programming patterns; avoid classes
- Prefer iteration and modularization to adhere to DRY principles
Nomenclature
- Use PascalCase for types and interfaces
- Use camelCase for variables, functions, and methods
- Use kebab-case for file and directory names
- Use UPPERCASE for environment variables
- Use descriptive variable names with auxiliary verbs:
isLoading,hasError,canDelete - Start each function with a verb
Functions
- Write short functions with a single purpose
- Use arrow functions for simple operations
- Use async/await consistently throughout the codebase
- Use the RO-RO pattern (Receive an Object, Return an Object) for multiple parameters
Types and Interfaces
- Prefer interfaces over types for object shapes
- Avoid enums; use maps or const objects instead
- Use Zod for runtime validation with inferred types
- Use
readonlyfor immutable properties - Use
import typefor type-only imports
Fastify-Specific Guidelines
Project Structure
Route Organization
- Organize routes by resource/domain
- Use route plugins for modular registration
- Define schemas alongside route handlers
- Use route prefixes for API versioning
Schema Validation with JSON Schema / Ajv
- Define JSON schemas for all request/response validation
- Use @sinclair/typebox for type-safe schema definitions
- Leverage Fastify's built-in Ajv integration
Plugins and Decorators
- Use plugins for shared functionality
- Decorate Fastify instance with services and utilities
- Register plugins with proper encapsulation
Prisma Integration
- Use Prisma as the ORM for database operations
- Create repository classes for data access
- Use transactions for complex operations
Error Handling
- Use Fastify's built-in error handling
- Create custom error classes for domain errors
- Return consistent error responses
Testing with Jest
- Write unit tests for services and handlers
- Use integration tests for routes
- Mock external dependencies
Performance
- Fastify is one of the fastest Node.js frameworks
- Use schema validation for automatic serialization optimization
- Enable logging only when needed in production
- Use connection pooling for database connections
Security
- Use @fastify/helmet for security headers
- Implement rate limiting with @fastify/rate-limit
- Use @fastify/cors for CORS configuration
- Validate all inputs with JSON Schema
- Use JWT for authentication with @fastify/jwt


