An enterprise-grade NestJS API for an e-commerce store built with Domain-Driven Design, Hexagonal Architecture, and modern best practices.
- What Is This?
- π Quick Start
- Architecture at a Glance
- β Feature Catalog
- π Documentation Index
- π§ Roadmap
- π§ͺ Testing
- ποΈ Project Structure
- π License
A production-grade e-commerce API built as a modular monolith with NestJS and TypeScript. The codebase implements Domain-Driven Design (both Strategic and Tactical), Hexagonal Architecture, and the distributed systems patterns that most tutorials skip β SAGA orchestration with compensation, strict bounded context isolation via ACL Gateways, Redis-backed idempotency, structured observability, and a full RSA-based auth stack with refresh token rotation and RBAC.
Designed as a reference for how to build enterprise backend systems that are testable, maintainable, and production-ready from day one.
- Node.js β₯ 22 Β· npm β₯ 11 Β· Docker Desktop β₯ 28 Β· Git β₯ 2.49
# 1. Clone & install
git clone https://github.com/raouf-b-dev/ecommerce-store-api.git
cd ecommerce-store-api
npm install
# 2. Generate environment files
npm run env:init
# 3. Update .env.* files with your secrets (DB, Redis, JWT keys)
# 4. Start infrastructure & run migrations
npm run d:up:dev
npm run migration:run:dev
# 5. Start the API
npm run start:devThe API will be available at http://localhost:3000 π
π‘ API Documentation β full endpoint specs, schemas, and auth requirements via Swagger UI: http://localhost:3000/api
# Start API + PostgreSQL + Redis + Prometheus + Loki + Tempo + Grafana
npm run d:up:full:prodGrafana dashboards will be available at http://localhost:3000 (Grafana port) with pre-provisioned datasources and dashboards.
graph TD
Client["π± Client App (Web/Mobile)"] -->|HTTP/REST| API["π‘οΈ NestJS API Gateway"]
Client -->|WebSocket| WS["π WebSocket Gateway"]
subgraph "Application Core (Modular Monolith)"
API --> Auth["π Auth Module"]
API --> Orders["π¦ Orders Module"]
API --> Products["π·οΈ Products Module"]
API --> Carts["π Carts Module"]
API --> Payments["π³ Payments Module"]
API --> Inventory["π Inventory Module"]
API --> Customers["π₯ Customers Module"]
WS --> Notifications["π Notifications Module"]
Orders -->|SAGA Orchestration| Inventory
Orders -->|SAGA Orchestration| Payments
Orders -->|Event| Notifications
end
subgraph "Infrastructure Layer"
Auth -->|Persist| PG["π PostgreSQL"]
Orders -->|Persist| PG
Products -->|Persist| PG
Carts -->|Cache/Persist| Redis["β‘ Redis Stack"]
Products -->|Search| Redis
Orders -->|Async Jobs| BullMQ["π BullMQ Job Queue"]
Notifications -->|Async Jobs| BullMQ
end
subgraph "Observability Layer"
API -->|Structured Logs| Loki["π Loki"]
API -->|Metrics /metrics| Prometheus["π Prometheus"]
API -->|Traces OTLP| Tempo["π Tempo"]
Loki --> Grafana["π Grafana"]
Prometheus --> Grafana
Tempo --> Grafana
end
subgraph "External Services"
Payments <-->|Verify| Stripe["π³ Payment Gateway"]
end
See the full System Architecture & Diagrams for C4, sequence, and class diagrams.
Every feature links to detailed documentation in
docs/FEATURES.mdand/or the relevant source code.
| Feature | Description | Location |
|---|---|---|
| Strategic DDD | Subdomains, Bounded Contexts, Context Mapping | ARCHITECTURE.md |
| Tactical DDD | Entities, Value Objects, Aggregates, Domain Services | src/modules/*/core/domain/ |
| Hexagonal Architecture | Ports & Adapters β infrastructure-agnostic domain core | DDD-HEXAGONAL.md |
| ACL Gateway Pattern | 7 gateway ports decoupling 8 bounded contexts | INTEGRATION-PATTERNS.md |
| Modular Monolith | 9 isolated modules, microservice-extraction ready | src/modules/ |
| Result Pattern | Functional Result<T, E> replacing exception-driven flow |
src/shared-kernel/domain/ |
| Feature | Description | Location |
|---|---|---|
| SAGA Orchestration | Multi-step checkout with automatic compensation on failure | src/modules/orders/primary-adapters/jobs/ |
| Idempotency | Redis-backed @Idempotent() decorator β execute-exactly-once |
src/infrastructure/idempotency/ |
| BullMQ Nested Flows | Composed background job pipelines for notifications | src/modules/notifications/ |
| Hybrid Payment Strategy | Unified COD + Online checkout via Strategy Pattern | src/modules/payments/ |
| Feature | Description | Location |
|---|---|---|
| RedisJSON | Cart storage as native JSON documents β no SQL joins | src/modules/carts/secondary-adapters/ |
| RedisSearch | Full-text search and filtering from Redis | src/modules/products/secondary-adapters/ |
| Cache-Aside Decorator | Transparent CachedRepository wrapping Postgres with Redis |
src/modules/*/secondary-adapters/repositories/cached-*/ |
| Feature | Description | Location |
|---|---|---|
| RSA JWT (RS256 + JWKS) | Production-grade auth with public key distribution endpoint | JWT-RSA-JWKS.md |
| Refresh Token Rotation | Session-based tokens with SHA-256 hashing + HttpOnly cookies | src/modules/auth/ |
| RBAC System | Database-backed Roles & Permissions with PermissionsGuard |
src/modules/auth/core/domain/ |
| API Rate Limiting | Redis-backed throttling via @nestjs/throttler |
src/infrastructure/throttler/ |
| Helmet Headers | Standard security headers (HSTS, X-Frame-Options, etc.) | src/main.ts |
| CORS Whitelist | Environment-based origin restriction β no wildcards in prod | src/config/ |
| XSS Sanitization | Global sanitize-html interceptor on all request bodies |
src/interceptors/ |
| Pagination Safety | @Max(100) on all query DTOs to prevent resource exhaustion |
src/modules/*/primary-adapters/dtos/ |
| Feature | Description | Location |
|---|---|---|
| Multi-Stage Docker | 4-stage build, Node.js 24 Alpine, tini PID 1, non-root user | Dockerfile |
| Graceful Shutdown | Signal handling, connection draining, worker cleanup | PROCESS-LIFECYCLE.md |
| Health Checks | GET /health via @nestjs/terminus (Postgres + Redis + WS) |
src/modules/health/ |
| API Versioning | URI-based versioning (/v1/) for all API endpoints |
src/modules/*/ |
| Admin Seeder | Bootstrap admin user and role/permission data on first deploy | ADMIN-BOOTSTRAP.md |
| Multi-Env Config | 4 profiles with type-safe validation + secrets separation | SECRETS-MANAGEMENT.md |
| Feature | Description | Location |
|---|---|---|
| Structured Logging | Winston JSON logging shipped to Loki via Promtail | src/infrastructure/logging/ |
| Correlation IDs | X-Request-Id propagated through HTTP + all 18 BullMQ jobs |
src/infrastructure/logging/ |
| Prometheus Metrics | RED method metrics + business telemetry via prom-client |
src/infrastructure/metrics/ |
| Distributed Tracing | OpenTelemetry auto-instrumentation exporting to Tempo via OTLP gRPC | src/infrastructure/tracing/ |
| Grafana Stack | Pre-provisioned dashboards with Loki, Prometheus, and Tempo datasources | MONITORING-STACK-GUIDE.md |
| Domain Event Metrics | Business events (login, order, payment) published and tracked | src/infrastructure/metrics/listeners/ |
| CI/CD Pipeline | GitHub Actions: lint β build β test β publish | .github/workflows/ |
| Feature | Description | Location |
|---|---|---|
| Unit + Integration Suite | Domain logic, use cases, repositories, controllers | src/modules/*/ |
| Test Factories | Scenario-specific domain object builders per module | src/modules/*/testing/ |
| Typed Mock Repos | Interface-compliant mocks with test helper methods | src/modules/*/testing/ |
| Document | Description |
|---|---|
| FEATURES.md | Detailed feature documentation with code locations |
| docs/README.md | Unified technical documentation index |
| ARCHITECTURE.md | C4 system context, domain flows, sequence diagrams |
| DDD-HEXAGONAL.md | Canonical DDD & Hexagonal Architecture rules |
| INTEGRATION-PATTERNS.md | ACL Gateway, SAGA, Domain Events, Outbox |
| JWT-RSA-JWKS.md | RSA JWT implementation and JWKS endpoint details |
| SECRETS-MANAGEMENT.md | Configuration taxonomy and key rotation |
| ADMIN-BOOTSTRAP.md | Admin seeding, role/permission initialization |
| MONITORING-STACK-GUIDE.md | Grafana, Prometheus, Loki, Tempo setup and usage |
| Observability Architecture | Signal pipeline diagram (logs, metrics, traces β Grafana) |
| PROCESS-LIFECYCLE.md | PIDs, signals, and graceful shutdown deep-dive |
| ROADMAP.md | Production readiness checklist with prioritized tasks |
| TROUBLESHOOTING.md | Common issues and solutions |
| AGENT.md | Coding guidelines and conventions |
This project is continuously evolving. See the full ROADMAP.md for completed phases, current work, and upcoming features.
npm test # Run all unit tests
npm run test:cov # Generate coverage report
npm run test:e2e # End-to-end tests
npm run test:ci # CI mode (GitHub Actions)src/
βββ shared-kernel/ # Pure domain building blocks (Result, Value Objects, base UseCase)
βββ infrastructure/ # Global secondary adapters (DB, Redis, BullMQ, JWT, logging, WebSocket)
βββ interceptors/ # Global Result Interceptor
βββ modules/ # Feature Modules (Bounded Contexts)
β βββ [module]/
β βββ core/domain/ # Entities, Value Objects, Repository Ports
β βββ core/application/# Use Cases & Application Services
β βββ primary-adapters/# DTOs, Controllers, Job Handlers, Listeners
β βββ secondary-adapters/# Repositories, Gateways, Schedulers
β βββ testing/ # Module-specific mocks & factories
βββ config/ # Environment validation & configuration
βββ main.ts # Application bootstrap
For strict DDD and Hexagonal Architecture definitions, see DDD-HEXAGONAL.md.
Released under the MIT License.
Built by Abderaouf .B Β· Issues Β· Repository