An enterprise-level NestJS MVP API for an e-commerce store built with Domain-Driven Design, Clean Architecture, and modern best practices.
- π Key Features
- π Advanced Engineering Features
- π― Recruiter's Guide
- π Quick Start
- π§ͺ Testing
- ποΈ Database Management
- π³ Docker & Infrastructure
- ποΈ Project Architecture
- π§ Environment Configuration
- π Available Scripts
- π¦ API Endpoints
- π Security & Best Practices
- π οΈ Troubleshooting
- οΏ½ Roadmap
- οΏ½π Project Statistics
- π Contributing
- ποΈ System Architecture
- π License
- π€ Acknowledgments
- π Support
"The main goal when I started building this API was to learn new stuff that I did not know before... I reinforced my knowledge on DDD, I learned how to effectively create a scalable system, separate concerns, separate business logic from technical logic..."
I built this project not just as another e-commerce demo, but as a deep dive into Enterprise Node.js Architecture. My goal was to bridge the gap between "tutorial code" and "production systems" by implementing the hard parts that most courses skip:
- Distributed Systems: Handling eventual consistency with SAGA pattern & RabbitMQ/BullMQ.
- Fail-Safe Mechanisms: Designing compensation flows when things go wrong (e.g., payment succeeds but inventory fails).
- Strict DDD: Enforcing boundaries between Domain, Application, and Infrastructure layers.
- Testing Culture: Writing 50+ test suites because in the real world, tests are not optional.
I built this to prove (to myself and future employers) that I can handle complex, scalable backend systems. I hope it serves as a valuable reference for others on the same journey!
- Domain-Driven Design (DDD) with clear layer separation (Domain, Application, Infrastructure, Presentation)
- Strategic DDD with explicit Subdomains (Core, Generic, Supporting) and Bounded Contexts
- Anti-Corruption Layer (ACL) using Ports & Adapters to decouple modules
- Clean Architecture principles ensuring the core logic is independent of frameworks and external tools
- Result Pattern for consistent, type-safe error handling across the entire application
- Hexagonal Architecture (Ports & Adapters) for easy swapping of infrastructure components (e.g., switching between Postgres and Redis repositories)
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 "External Services"
Payments <-->|Verify| Stripe["π³ Payment Gateway"]
end
Key Strength: Fully supports Hybrid Payment Orchestration (Online + Cash-on-Delivery), handling complex state transitions for both synchronous and asynchronous flows.
See the full System Architecture & Diagrams for detailed Sequence and Class diagrams.
- NestJS - Enterprise-grade Node.js framework
- PostgreSQL with TypeORM - Relational data with automated migrations
- Redis Stack - Utilizing RedisJSON for document storage and RedisSearch for ultra-fast product indexing
- BullMQ - Robust message queue for handling asynchronous background jobs and distributed tasks
- Docker Compose - Fully containerized environment for consistent development and deployment
- Comprehensive Unit Testing with Jest
- High Test Coverage across all layers
- GitHub Actions CI/CD with automated testing
- ESLint + Prettier for code quality
- Type-safe environment configuration
- Order Processing - Complex order lifecycle with SAGA orchestration and compensation logic
- Product Catalog - Advanced product management with RedisSearch indexing and filtering
- Shopping Carts - High-performance cart management with RedisJSON persistence
- Inventory Management - Real-time stock tracking and reservation system
- Customer Profiles - Management of user data, shipping addresses, and preferences
- Payment Orchestration - Strategy-based handling of Online and COD payment flows
- Authentication - Secure JWT-based identity and access management
- Notifications - Real-time WebSocket and background alert delivery system
This project goes beyond a simple CRUD API by implementing complex distributed systems patterns:
- Problem: Network retries can lead to duplicate orders or payments.
- Solution: Implemented a custom
@Idempotent()decorator and interceptor using Redis as a distributed lock and result cache. This ensures that critical operations (like checkout) are executed exactly once, even if the client retries the request.
- Problem: In a distributed system, if one step of a multi-stage process (like checkout) fails, the system must revert previous successful steps.
- Solution: Implemented a
CheckoutFailureListenerthat monitors BullMQ job failures. If a checkout fails after payment or stock reservation, it automatically triggers compensation logic:- Releasing stock reservations
- Processing payment refunds
- Cancelling the pending order
- RedisJSON: Stores complex product and cart data as JSON documents, reducing the need for expensive SQL joins for frequently accessed data.
- RedisSearch: Provides full-text search and advanced filtering on product data directly from Redis, significantly improving performance compared to traditional SQL
LIKEqueries.
- Problem: Real-world e-commerce systems need to handle both immediate payments (Credit Card) and deferred confirmations (Cash on Delivery) without duplicating business logic.
- Solution: Designed a unified Strategy Pattern for checkout flows.
- Online: Full SAGA (Validate -> Reserve -> Pay -> Confirm).
- COD: Async Pause (Validate -> Reserve -> Stop & Wait -> Manual Confirm).
- Checks shared stock availability logic while respecting different lifecycle requirements.
If you are a recruiter or hiring manager, here is why this project demonstrates senior-level engineering skills:
- Architectural Depth: Most "e-commerce" tutorials stop at simple controllers. This project implements full DDD, showing an understanding of how to manage complexity in large-scale systems.
- Reliability Engineering: The use of Idempotency and Compensation Logic shows a "production-first" mindset where data consistency and system reliability are prioritized.
- Modern Infrastructure: Proficiency with Redis Stack, BullMQ, and Docker demonstrates the ability to design and manage modern, scalable infrastructure.
- Testing Excellence: High test coverage (Unit, Integration, and E2E) proves a commitment to code quality and long-term maintainability.
Ensure you have the following installed:
- Node.js β₯ 22 (tested with v22.14.0)
- npm β₯ 11 (tested with v11.4.2)
- Docker Desktop β₯ 28 (tested with v28.3.2)
- Docker Compose v2 (
docker composecommand) - Git β₯ 2.49
-
Clone the repository
git clone https://github.com/raouf-b-dev/ecommerce-store-api.git cd ecommerce-store-api -
Install dependencies
npm install
-
Generate environment files
# Generate all environment files npm run env:init # Or generate specific environment npm run env:init:dev
-
Configure environment variables
Update the generated
.env.*files with your secrets:- Database credentials
- Redis configuration
- JWT secrets
- Other service configurations
-
Start infrastructure services
npm run d:up:dev
-
Run database migrations
npm run migration:run:dev
-
Start the development server
npm run start:dev
The API will be available at http://localhost:3000 π
π API Documentation: http://localhost:3000/api (Swagger UI)
Our testing strategy ensures high code quality and reliability:
# Run all tests
npm test
# Watch mode for development
npm run test:watch
# Generate coverage report
npm run test:cov
# Run E2E tests
npm run test:e2e
# CI mode (used in GitHub Actions)
npm run test:ci
- Unit Tests: Domain logic, services, and utilities
- Integration Tests: Database interactions and Redis caching
- E2E Tests: Complete API endpoint testing
- Coverage Reporting: Detailed coverage metrics with Jest
# Generate migration from entity changes
npm run migration:generate:dev -- CreateProductTable
# Create empty migration
npm run migration:create:dev -- AddProductIndex
# Run pending migrations
npm run migration:run:dev
# Revert last migration
npm run migration:revert:dev
# Show migration status
npm run migration:show:dev
Replace :dev with :prod, :staging, or :test for different environments.
# Development environment
npm run d:up:dev # Start services
npm run d:down:dev # Stop services
npm run d:reset:dev # Reset with fresh data
# Production environment
npm run d:up:prod
npm run d:down:prod
npm run d:reset:prod
# Other environments: staging, test
npm run d:up:staging
npm run d:up:test
- PostgreSQL 16.3 - Primary database
- Redis Stack 7.2 - Caching and search (includes RedisJSON & RedisSearch)
- Custom networking for service communication
src/
βββ core/ # Shared kernel & cross-cutting concerns
β βββ domain/ # Base entities, value objects, & Result pattern
β βββ application/ # Common application services & interfaces
β βββ infrastructure/ # Shared persistence, decorators, & interceptors
βββ modules/ # Feature-based modules (Bounded Contexts)
β βββ [module]/ # e.g., orders, products, inventory
β β βββ domain/ # Entities, Value Objects, & Repository interfaces
β β βββ application/ # Use Cases & Application services
β β βββ infrastructure/ # Repository implementations & external clients
β β βββ presentation/ # Controllers, DTOs, Listeners, & Jobs
β β βββ testing/ # Module-specific factories, mocks, & builders
β β βββ [module].module.ts
βββ config/ # Global configuration & environment validation
βββ shared/ # Generic utilities & helper functions
βββ testing/ # Root-level testing utilities & E2E setup
βββ main.ts # Application bootstrap
- Dependency Inversion: High-level modules don't depend on low-level modules
- Single Responsibility: Each class has one reason to change
- Open/Closed: Open for extension, closed for modification
- Interface Segregation: Many client-specific interfaces
.env.development- Development settings.env.staging- Staging environment.env.production- Production configuration.env.test- Testing environment.env.example- Template with all required keys
- Database Connection (PostgreSQL)
- Redis Configuration (connection, keyspace)
- JWT Authentication (secrets, expiration)
- API Settings (port, CORS, rate limiting)
start:dev- Start in watch modestart:debug- Start with debuggingbuild- Build for productionlint- Run ESLint with auto-fix
test- Run unit teststest:watch- Run tests in watch modetest:cov- Generate coverage reporttest:e2e- Run end-to-end teststest:ci- Run tests in CI mode
migration:generate:*- Generate new migrationmigration:run:*- Apply migrationsmigration:revert:*- Rollback migration
d:up:*- Start environment servicesd:down:*- Stop environment servicesd:reset:*- Reset environment with fresh data
env:init- Generate all environment filesclean- Remove build artifacts
| Module | Method | Endpoint | Description |
|---|---|---|---|
| Auth | POST |
/api/auth/register |
Register a new user |
POST |
/api/auth/login |
Authenticate and get JWT | |
| Products | GET |
/api/products |
List products with filtering/pagination |
GET |
/api/products/:id |
Get detailed product information | |
| Cart | POST |
/api/carts |
Create or retrieve active cart |
POST |
/api/carts/items |
Add item to cart with stock check | |
| Orders | POST |
/api/orders/checkout |
Process checkout (SAGA Pattern) |
GET |
/api/orders |
List user order history | |
| Notifications | GET |
/api/notifications |
Get real-time user notifications |
The full API specification, including request/response schemas and authentication requirements, is available via Swagger UI:
π http://localhost:3000/api/docs (when running locally)
- JWT Authentication with secure token handling
- Input Validation with class-validator decorators
- SQL Injection Prevention with TypeORM query builders
- CORS Configuration for cross-origin requests
- Rate Limiting (configurable per endpoint)
- TypeScript for compile-time type checking
- ESLint + Prettier for consistent code style
- Husky Git Hooks for pre-commit validation
- Environment-based Configuration for different deployment stages
- Comprehensive Error Handling with custom exceptions
# Check if ports are in use
lsof -i :5432 # PostgreSQL
lsof -i :6379 # Redis
# Reset Docker environment
npm run d:reset:dev
# Ensure database is running
npm run d:up:dev
# Check connection with migration status
npm run migration:show:dev
# Reset database if needed (β οΈ DATA LOSS)
npm run d:reset:dev
npm run migration:run:dev
# Run tests in isolation
npm run test:ci
# Check for open handles
npm run test -- --detectOpenHandles
# Ensure test database is clean
npm run d:reset:test
- Verify all required environment variables are set
- Check
.env.examplefor the complete list of required keys - Ensure Docker services are healthy before running the application
This project is continuously evolving. Here are the planned features and improvements:
- Real Payment Integration: Support for Stripe, PayPal, and other gateways.
- Advanced Analytics: Reporting dashboard for sales, inventory, and customer behavior.
- Real-time Notifications: WebSockets/SSE for order status updates and stock alerts.
- E2E Testing Suite: Comprehensive end-to-end tests using Supertest and Testcontainers.
- Performance Benchmarking: Detailed load testing and optimization reports.
- API Versioning: Implementing a robust versioning strategy for long-term support.
- Admin Dashboard: A modern frontend for store management (Angular/React).
- Customer Storefront: A high-performance web application built with Angular.
- Languages: TypeScript 100%
- Test Coverage: High (run
npm run test:covfor details) - Build Status: Automated CI/CD with GitHub Actions
- Dependencies: Always up-to-date with security patches
Released under the MIT License. Feel free to use, modify, and distribute this code for personal or commercial projects.
- NestJS Team for the excellent framework
- TypeORM for robust database management
- Redis for high-performance caching
- Jest for comprehensive testing capabilities
For questions, issues, or contributions:
- GitHub Issues: Report bugs or request features
- GitHub Repository: https://github.com/raouf-b-dev/ecommerce-store-api
Built with β€οΈ by Abderaouf .B
Crafting enterprise-level APIs with clean architecture and modern best practices