WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

This is a repository meant to serve as a starting point if you want to start a TypeScript express API project with some common features already set up and best practices.

Notifications You must be signed in to change notification settings

Proskynete/node-api-skeleton

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Node API Skeleton

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

CI Lint GitHub issues GitHub forks GitHub stars PRs welcome

πŸŽ‰ 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
  1. Highlights
  2. Features
  3. Architecture
  4. Folder Structure
  5. Quick Start
  6. Docker
  7. API Endpoints
  8. Testing
  9. Observability
  10. Documentation

✨ 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

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

πŸ—οΈ 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

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

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 entity
  • Message.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

See test/contract/README.md

πŸ“Š 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 latency
  • http_requests_total - Total requests
  • http_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:

πŸ“š Documentation

Core Documentation

  • 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

View all ADRs β†’

Testing Guides

Integration Guides

Utility Scripts

🎯 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

(⬆️ Back to top)

About

This is a repository meant to serve as a starting point if you want to start a TypeScript express API project with some common features already set up and best practices.

Topics

Resources

Stars

Watchers

Forks

Contributors 2

  •  
  •