Production-ready Node.js API skeleton built with Hexagonal Architecture, Fastify, TypeScript, DDD, and modern best practices. Perfect starting point for scalable, maintainable API projects.
Status
๐ Architecture Status: PRODUCTION READY
Version 2.0 - Migration to Hexagonal Architecture + Fastify COMPLETED!
All 8 migration stages completed โ
- โ Stage 0: SWC compiler, Fastify dependencies, path aliases
- โ Stage 1: Hexagonal folder structure, Zod validation, Fastify server
- โ Stage 2: Domain layer (entities, value objects, ports)
- โ Stage 3: Application layer (use cases, DTOs, mappers)
- โ Stage 4: Infrastructure layer (controllers, routes, repositories)
- โ Stage 5: Dependency Injection with Awilix
- โ Stage 6: Observability (Winston logging + Prometheus metrics)
- โ Stage 7: Testing (Vitest + k6 performance tests)
- โ Stage 8: Cleanup, documentation, Docker production setup
๐ Table of Contents
๐ Using as Template
This skeleton is designed to be used as a starting point for your Node.js API projects. You have two options:
Option 1: Use as GitHub Template (Recommended)
- Click the "Use this template" button at the top of this repository
- Create your new repository with your project name
- Clone your new repository
- Follow the Setup Guide to customize for your project
Option 2: Clone and Explore First
Want to explore the skeleton before committing?
# Clone this repository git clone https://github.com/Proskynete/node-api-skeleton.git cd node-api-skeleton # Install dependencies npm install # Start development server npm run dev
Visit http://localhost:3000/api/v1/greetings to see it in action!
Once you're ready to use it as a template, follow the Setup Guide.
โจ Highlights
๐๏ธ Modern Architecture
- Hexagonal Architecture (Ports & Adapters) for clean separation of concerns
- Onion Architecture with dependency inversion
- Screaming Architecture - folder structure reflects business capabilities
- DDD (Domain-Driven Design) with entities, value objects, and aggregates
- Vertical Slice organization by bounded contexts
โก Performance
- Fastify - 2x faster than Express
- SWC - Ultra-fast TypeScript compiler (20x faster than tsc)
- Build time: ~56ms (was ~2-3s with tsc)
- Production-ready with Docker multi-stage builds
๐งช Testing & Quality
- Vitest - Lightning-fast unit & integration tests
- k6 - Performance/load testing with thresholds
- 98%+ coverage - 244 comprehensive tests across all layers
- Type-safe validation with Zod
- ESLint + Prettier - Code quality enforcement
๐ Observability
- Winston - Structured JSON logging
- Prometheus - Metrics collection (requests, latency, errors)
- Grafana - Metrics visualization
- Health checks - Liveness & readiness probes
- OpenAPI - Interactive API documentation
๐ณ DevOps Ready
- Docker multi-stage builds (minimal Alpine images)
- Docker Compose stacks for dev & production
- Non-root user for security
- Health checks integrated
- Prometheus + Grafana stack included
โ๏ธ Features
Core Stack
- โ Fastify - High-performance web framework
- โ TypeScript - Type-safe JavaScript
- โ SWC - Ultra-fast TypeScript compiler
- โ Zod - Runtime schema validation
- โ Awilix - Dependency injection
Testing
- โ Vitest - Fast unit & integration tests
- โ Supertest - HTTP endpoint testing
- โ k6 - Load & performance testing
- โ Pact - Contract testing framework
- โ Coverage reports with v8
Observability
- โ Winston - Structured logging
- โ Prometheus - Metrics collection
- โ prom-client - Prometheus client
- โ Health checks (liveness/readiness)
- โ Swagger/OpenAPI - API documentation
Security & Best Practices
- โ @fastify/helmet - Security headers
- โ @fastify/cors - CORS support
- โ @fastify/rate-limit - Rate limiting
- โ Environment validation with Zod
- โ Docker non-root user
- โ Immutable domain entities
- โ ADRs (Architecture Decision Records)
Development Tools
- โ ESLint - Code linting
- โ Prettier - Code formatting
- โ Husky - Git hooks
- โ lint-staged - Pre-commit checks
- โ Nodemon - Dev server auto-reload
๐๏ธ Architecture
Hexagonal Architecture
The application follows Hexagonal Architecture (Ports & Adapters):
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Infrastructure (Adapters) โ โ Fastify, DB, External APIs
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Application (Use Cases) โ โ Business orchestration
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Domain (Business Logic) โ โ Pure business rules
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Dependency Rule: Dependencies point inward only
- Infrastructure โ Application โ Domain
- Domain has zero framework dependencies
Vertical Slice by Contexts
Each bounded context is a complete vertical slice:
@contexts/greetings/
โโโ domain/ # Entities, Value Objects, Business Rules
โโโ application/ # Use Cases, DTOs, Mappers, Ports
โโโ infrastructure/ # Controllers, Routes, Repositories
Benefits:
- High cohesion - related code lives together
- Easy to navigate - no jumping between layers
- Scalable - add new contexts without touching existing ones
- Microservices-ready - easy to extract contexts
See ARCHITECTURE.md for complete documentation.
๐ Folder Structure
src/
โโโ @contexts/ # Business Features (Bounded Contexts)
โ โโโ greetings/
โ โโโ domain/ # Business Logic (framework-independent)
โ โ โโโ entities/ # Greeting entity
โ โ โโโ value-objects/ # Message value object
โ โ โโโ exceptions/ # Domain exceptions
โ โโโ application/ # Use Cases & Orchestration
โ โ โโโ v1/ # API version 1
โ โ โ โโโ use-cases/ # GetGreetingUseCase
โ โ โ โโโ dtos/ # Request/Response DTOs
โ โ โ โโโ mappers/ # Domain โ DTO transformation
โ โ โ โโโ ports/ # Interfaces (inbound/outbound)
โ โ โโโ v2/ # API version 2 (enhanced)
โ โโโ infrastructure/ # Adapters (HTTP, DB, External)
โ โโโ http/ # Controllers & Routes (v1, v2)
โ โโโ persistence/ # Repository implementations
โ
โโโ @shared/ # Cross-Cutting Concerns
โ โโโ domain/ # Shared domain concepts
โ โโโ infrastructure/
โ โ โโโ config/ # Environment, DI container
โ โ โโโ http/ # Fastify app, plugins
โ โ โโโ observability/ # Winston, Prometheus
โ โโโ types/ # Common types
โ โโโ utils/ # Pure utility functions
โ โโโ constants/ # HTTP status codes, etc.
โ
โโโ @app/ # Application Bootstrap
โ โโโ server/ # Fastify configuration
โ
โโโ main.ts # Entry point
๐ Quick Start
Note: These instructions are for exploring the skeleton. If you've already created a project from this template, see the Setup Guide instead.
Prerequisites
- Node.js >= 20
- npm >= 10
- Docker (optional, for containerized setup)
- k6 (optional, for performance tests)
Installation
# Clone repository git clone https://github.com/Proskynete/node-api-skeleton.git cd node-api-skeleton # Install dependencies npm install # Copy environment file cp .env.example .env # Start development server npm run dev
The API will be running at http://localhost:3000
Available Scripts
# Development npm run dev # Start dev server with hot reload (SWC) npm run build # Build production bundle (SWC) npm start # Run production server # Testing npm run test # Run all tests (Vitest) npm run test:watch # Run tests in watch mode npm run test:ui # Run tests with UI dashboard npm run test:coverage # Generate coverage report # Performance Testing (k6) npm run test:performance:v1 # Test v1 endpoint npm run test:performance:v2 # Test v2 endpoint npm run test:performance:load # Full load test # Code Quality npm run lint # Check linting npm run lint:fix # Fix linting issues npm run format # Format code with Prettier npm run format:check # Check formatting
๐ณ Docker
The project uses Docker Compose profiles for managing development and production environments in a single configuration file.
Production Environment
# Start production stack (API + Prometheus + Grafana) docker-compose --profile production up -d # View logs docker-compose logs -f api-prod # Stop services docker-compose --profile production down
Development Environment
# Start dev environment with hot reload docker-compose --profile dev up -d # View logs docker-compose logs -f api-dev # Stop services docker-compose --profile dev down
Services
- API: http://localhost:3000
- Prometheus: http://localhost:9090
- Grafana: http://localhost:3001 (admin/admin)
See DOCKER.md for complete documentation.
๐ก API Endpoints
Health & Metrics
- Liveness:
GET /health/live- Is the app running? - Readiness:
GET /health/ready- Can it serve traffic? - Metrics:
GET /metrics- Prometheus metrics - Docs:
GET /docs- Swagger UI
Greetings API (v1)
- Get Greeting:
GET /api/v1/greetings
Greetings API (v2)
- Get Greeting (enhanced):
GET /api/v2/greetings
API Versioning: Multiple versions coexist, sharing the same domain layer but with different use cases.
๐งช Testing
Comprehensive Test Suite
The project includes 244 tests across all layers with excellent coverage:
Coverage Stats (as of v2.1.0):
- โ Statements: 98.42%
- โ Branches: 84.00%
- โ Functions: 96.87%
- โ Lines: 98.38%
Coverage Thresholds: 80% minimum for all metrics
Unit Tests
Test business logic in isolation:
npm run test # Run all tests npm run test:watch # Watch mode npm run test:ui # Interactive UI dashboard npm run test:coverage # Generate coverage report
Test Coverage by Layer:
Domain Layer (Pure business logic):
DomainEvent.spec.ts- Base domain event class (12 tests)GreetingCreatedEvent.spec.ts- Greeting domain event (21 tests)Greeting.spec.ts- Greeting entityMessage.spec.ts- Message value object
Application Layer (Use cases & orchestration):
GetGreetingUseCase.spec.ts(v1 and v2) - Business workflows (19 tests each)GreetingMapper.spec.ts(v1 and v2) - Data transformations (29 tests v2)GreetingCreatedEventHandler.spec.ts- Event handling (13 tests)InMemoryDomainEventPublisher.spec.ts- Event publishing (29 tests)
Infrastructure Layer (Repositories):
InMemoryGreetingRepository.spec.ts- Data persistence (19 tests)
Architecture Principle: Infrastructure adapters (controllers, middlewares, plugins, route loaders) are excluded from unit test coverage as they're validated through integration/E2E tests. This aligns with Hexagonal Architecture best practices.
Integration Tests
Test HTTP endpoints and infrastructure:
describe("GET /api/v1/greetings", () => { it("should return greeting", async () => { const response = await request(app.server) .get("/api/v1/greetings") .expect(200); expect(response.body.message).toBe("Hello World!"); }); });
Integration Test Coverage:
- HTTP endpoints (v1 and v2)
- Rate limiting
- Health checks
- Metrics collection
- Error handling
Performance Tests (k6)
Load testing with strict performance thresholds:
npm run test:performance:v1 # Test v1 endpoint npm run test:performance:v2 # Test v2 endpoint npm run test:performance:load # Full load test
Performance Thresholds:
- p95 latency < 500ms
- p99 latency < 1000ms
- Error rate < 1%
- Request rate > 50 req/s
See test/performance/README.md
Contract Tests (Pact)
Consumer-driven contract testing ensures API compatibility:
npm run test:contract:provider
๐ Observability
Logging (Winston)
Structured JSON logging in production, pretty logs in development:
logger.info("Processing request", { requestId: request.id, version: "v1", });
Metrics (Prometheus)
Available at /metrics:
http_request_duration_seconds- Request latencyhttp_requests_total- Total requestshttp_requests_in_progress- Active requests
Health Checks
- Liveness:
/health/live- Basic health check - Readiness:
/health/ready- Dependency health (memory, DB, etc.)
OpenAPI Documentation
Interactive API docs at:
- Swagger UI: http://localhost:3000/docs
๐ Documentation
Core Documentation
- SETUP.md - Initial setup guide after using this template (start here!)
- ARCHITECTURE.md - Complete architecture guide (Hexagonal + DDD + Vertical Slices)
- DOCKER.md - Docker setup, multi-stage builds, and Docker Compose
- GITHUB_ACTIONS.md - CI/CD pipeline, workflows, and automation
- CLAUDE.md - Development guide for Claude Code AI assistant
Architecture Decision Records (ADRs)
Document key architectural decisions with context and consequences:
- ADR Index - Complete list of architectural decisions
- ADR-0001 - Hexagonal Architecture adoption
- ADR-0007 - Bounded Contexts organization
- ADR-0009 - OOP + FP hybrid approach
Testing Guides
- Performance Testing - k6 load testing, thresholds, and automated test runner
- Contract Testing - Provider - Pact provider tests for HTTP inbound adapters
- Contract Testing - Consumer - Pact consumer tests reference (HTTP outbound adapters)
- Contract Tests README - Contract testing overview and execution
Integration Guides
- Database Integration - Prisma setup and repository implementation guide
Utility Scripts
- Scripts README - Automated performance test runner documentation
๐ฏ Design Patterns
- Dependency Injection (Awilix)
- Factory Pattern (Entity creation)
- Mapper Pattern (Domain โ DTO)
- Repository Pattern (Data access)
- Strategy Pattern (API versioning)
๐ Security
- Helmet security headers
- CORS configuration
- Input validation with Zod
- Non-root Docker user
- Environment variable validation
๐ค Contributing
Contributions are welcome! Please read CONTRIBUTING.md for guidelines.
๐ License
This project is licensed under the MIT License.
๐ Acknowledgments
- Built with โค๏ธ using modern Node.js best practices
- Inspired by Clean Architecture, DDD, and Hexagonal Architecture principles
Version: 2.1.0 Status: Production Ready Architecture: Hexagonal + Onion + Screaming Last Updated: December 2024