A modern, high-performance REST API built with Fastify and TypeScript, featuring dependency injection, comprehensive testing, and production-ready architecture.
- π High Performance - Built with Fastify for exceptional speed
- π Type Safety - Full TypeScript implementation with strict typing
- ποΈ Clean Architecture - Modular design with dependency injection
- π§ͺ Comprehensive Testing - 87% test coverage with Vitest
- π API Documentation - Auto-generated OpenAPI/Swagger docs
- π‘οΈ Security First - Built-in security headers, CORS, and rate limiting
- π§ Developer Experience - Hot reload, linting, and pre-commit hooks
- π Production Ready - Structured logging, error handling, and graceful shutdown
- Node.js >= 18.0.0
- npm >= 8.0.0
# Clone the repository
git clone https://github.com/NeaDigitra/Fastify-TS-API.git
cd Fastify-TS-API
# Install dependencies
npm install
# Start development server
npm run dev
The API will be available at http://localhost:3000
Once the server is running, visit:
- Swagger UI:
http://localhost:3000/docs
- OpenAPI JSON:
http://localhost:3000/docs/json
src/
βββ config/ # Configuration and environment variables
β βββ constants.ts # API constants and HTTP codes
β βββ environment.ts # Environment validation with Zod
β βββ messages.ts # Centralized message templates
β βββ sample-data.ts # Sample data generation
βββ container/ # Dependency injection setup
β βββ container.ts # Awilix DI container configuration
βββ controllers/ # HTTP request handlers
β βββ health.controller.ts
β βββ user.controller.ts
βββ middleware/ # Custom middleware
β βββ error-handler.ts
β βββ request-logger.ts
βββ repositories/ # Data access layer
β βββ user.repository.ts
β βββ impl/
β βββ in-memory-user.repository.ts
βββ routes/ # Route definitions
β βββ health.ts
β βββ users.ts
βββ schemas/ # TypeBox validation schemas
β βββ health.schema.ts
β βββ response.schema.ts
β βββ user.schema.ts
βββ services/ # Business logic layer
β βββ user.service.ts
βββ types/ # TypeScript type definitions
β βββ index.ts
βββ utils/ # Utility functions
β βββ errors.ts
β βββ id-generator.ts
β βββ response.ts
βββ index.ts # Application entry point
# Development
npm run dev # Start development server with hot reload
npm run build # Build for production
npm start # Start production server
# Testing
npm test # Run tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Run tests with coverage report
# Code Quality
npm run lint # Run ESLint
npm run lint:fix # Fix ESLint issues
npm run format # Format code with Prettier
npm run typecheck # Run TypeScript type checking
GET /api/v1/health
- Basic health checkGET /api/v1/health/ready
- Readiness check with service status
GET /api/v1/users
- List all users (with pagination)GET /api/v1/users/:id
- Get user by IDPOST /api/v1/users
- Create new userPUT /api/v1/users/:id
- Update userDELETE /api/v1/users/:id
- Delete user
graph TD
A[Controllers] --> B[Services]
B --> C[Repositories]
C --> D[Data Sources]
E[Routes] --> A
F[Middleware] --> E
G[Schemas] --> A
H[Utils] --> B
The application uses Awilix for dependency injection, enabling:
- Loose coupling between components
- Easy testing with mock dependencies
- Scalable and maintainable architecture
Custom error hierarchy with proper HTTP status codes:
AppError
- Base error classNotFoundError
- 404 errorsValidationError
- 400 validation errorsDuplicateResourceError
- 409 conflict errors- And more...
The project includes comprehensive testing with 87% coverage:
# Run all tests
npm test
# Run with coverage
npm run test:coverage
# Watch mode for development
npm run test:watch
- Unit Tests - Individual component testing
- Integration Tests - API endpoint testing
- Error Scenario Testing - Edge cases and error handling
- Repository Testing - Data layer testing
Create a .env
file in the root directory:
# Server Configuration
NODE_ENV=development
PORT=3000
HOST=0.0.0.0
LOG_LEVEL=info
# API Configuration
API_PREFIX=/api/v1
APP_NAME=Fastify TS API
APP_VERSION=1.0.0
API_DESCRIPTION=A modern REST API built with Fastify and TypeScript
# Rate Limiting
RATE_LIMIT_MAX=100
RATE_LIMIT_WINDOW=60000
# Pagination
PAGINATION_DEFAULT_PAGE=1
PAGINATION_DEFAULT_LIMIT=10
PAGINATION_MAX_LIMIT=100
# Features
ENABLE_SAMPLE_DATA=true
All environment variables are validated using Zod with:
- Type coercion (string to number/boolean)
- Default values
- Validation rules
- Runtime type safety
- Helmet - Security headers
- CORS - Cross-origin resource sharing
- Rate Limiting - Request throttling
- Input Validation - Schema-based validation
- Error Sanitization - Safe error responses
Using Pino for high-performance logging:
- Request/response logging
- Error tracking with stack traces
- Configurable log levels
- Pretty printing for development
- Basic health endpoint
- Readiness checks with service status
- Graceful shutdown handling
# Example Dockerfile
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dist ./dist
EXPOSE 3000
CMD ["npm", "start"]
# Build the application
npm run build
# Start production server
npm start
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
- Follow TypeScript best practices
- Maintain test coverage above 85%
- Use conventional commit messages
- Ensure all linting rules pass
- Update documentation for new features
This project is licensed under the MIT License - see the LICENSE file for details.
- Fastify - Fast and low overhead web framework
- TypeScript - JavaScript with types
- Vitest - Blazing fast unit testing framework
- Awilix - Dependency injection container
If you have any questions or need help getting started:
- Check the API Documentation
- Review the examples
- Open an issue
Happy coding! π