MCPcopy Index your code
hub / github.com/CollatzConjecture/nestjs-clean-architecture

github.com/CollatzConjecture/nestjs-clean-architecture @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
270 symbols 664 edges 71 files 30 documented · 11%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

NestJS Clean Architecture with DDD, CQRS & Event Sourcing

This is an advanced boilerplate project implementing Domain-Driven Design (DDD), Clean Architecture, CQRS (Command Query Responsibility Segregation), Event Sourcing and MongoDB with NestJS. It provides a robust foundation for building scalable and maintainable enterprise-level applications with proper separation of concerns and clean dependency direction.

If you want more documentation about NestJS, click here Nest

📝 Note: This version uses MongoDB with Mongoose. If you prefer the PostgreSQL version with TypeORM, you can find it at the original repository: https://github.com/CollatzConjecture/nestjs-clean-architecture-postgres

A quick introduction to clean architecture

Clean Architecture

🚀 Features

Core Architecture

  • Clean Architecture: Enforces strict separation of concerns with proper dependency direction (Infrastructure → Application → Domain).
  • Domain-Driven Design (DDD): Pure business logic encapsulated in Domain Services, accessed through Repository Interfaces.
  • CQRS: Segregates read (Queries) and write (Commands) operations for optimized performance and scalability.
  • Event Sourcing: Uses an event-driven approach with sagas for orchestrating complex business processes.
  • Repository Pattern: Clean interfaces defined in Domain layer, implemented in Infrastructure layer.
  • Dependency Inversion: Domain layer depends only on abstractions, never on concrete implementations.

Proper Layer Separation

  • Domain Layer: Pure business logic, domain entities without framework dependencies, repository interfaces
  • Application Layer: Business orchestration, application services, CQRS coordination, framework-agnostic services
  • API Layer: HTTP controllers, DTOs, request/response handling, framework-specific HTTP concerns
  • Infrastructure Layer: Database implementations, external API calls, concrete repository classes, global services

Security & Authentication

  • JWT Authentication: Implements secure, token-based authentication with refresh token rotation.
  • Google OAuth2 Integration: Secure third-party authentication with Google accounts, including CSRF protection.
  • Role-Based Access Control (RBAC): Complete implementation with protected routes and role-based guards.
  • Secure Password Storage: Hashes passwords using bcrypt with salt rounds.
  • Sensitive Data Encryption: Encrypts sensitive fields (e.g., user emails) at rest in the database using AES-256-CBC.
  • Blind Indexing: Allows for securely querying encrypted data without decrypting it first.
  • CSRF Protection: OAuth flows protected against Cross-Site Request Forgery attacks using state parameters.

Infrastructure & Operations

  • MongoDB Integration: Utilizes Mongoose for structured data modeling with a NoSQL database.
  • Containerized Environment: Full Docker and Docker Compose setup for development and production.
  • Health Checks: Provides application health monitoring endpoints via Terminus.
  • Structured Logging: Advanced logging system with business-context awareness and dependency injection.
  • Application Metrics: Exposes performance metrics for Prometheus.
  • Data Visualization: Comes with a pre-configured Grafana dashboard for visualizing metrics.
  • Request Throttling: Built-in rate limiting to prevent abuse and ensure API stability.

Testing

  • Unit & Integration Tests: A suite of tests for domain, application, and infrastructure layers.
  • E2E Tests: End-to-end tests to ensure API functionality from request to response.
  • High Test Coverage: Configured to report and maintain high code coverage.
  • Mocking: Clear patterns for mocking database and service dependencies.

Getting Started

git clone https://github.com/CollatzConjecture/nestjs-clean-architecture
cd nestjs-clean-architecture

📁 Project Structure

.
├── doc/
│   ├── common.http              # Common API requests
│   └── users.http               # User-specific API requests
├── src/
│   ├── api/                     # API Layer (HTTP Controllers & DTOs)
│   │   ├── controllers/
│   │   │   └── *.controller.ts  # HTTP endpoints (auth, profile, hello)
│   │   ├── dto/
│   │   │   ├── auth/            # Authentication DTOs
│   │   │   │   └── *.dto.ts     # Login & register DTOs
│   │   │   └── *.dto.ts         # Profile management DTOs
│   │   └── api.module.ts        # API module configuration
│   ├── application/             # Application Layer (Business Orchestration)
│   │   ├── __test__/
│   │   │   └── *.spec.ts        # Application layer tests
│   │   ├── auth/
│   │   │   ├── command/         # Auth commands & handlers
│   │   │   │   ├── *.command.ts # Create/delete auth user commands
│   │   │   │   └── handler/
│   │   │   │       └── *.handler.ts # Command handlers
│   │   │   ├── events/          # Auth domain events
│   │   │   │   └── *.event.ts   # User created/deleted events
│   │   │   ├── sagas/
│   │   │   │   └── *.saga.ts    # Registration flow orchestration
│   │   │   ├── decorators/
│   │   │   │   └── *.decorator.ts # Custom decorators (roles)
│   │   │   ├── guards/
│   │   │   │   └── *.guard.ts   # Authentication & authorization guards
│   │   │   ├── *.strategy.ts    # Auth strategies (JWT, local, Google OAuth)
│   │   │   └── auth.module.ts   # Auth module configuration
│   │   ├── decorators/
│   │   │   └── *.decorator.ts   # Global decorators (current user)
│   │   ├── interfaces/
│   │   │   └── *.interface.ts   # Application interfaces
│   │   ├── interceptors/
│   │   │   └── *.interceptor.ts # Request logging interceptors
│   │   ├── middlewere/
│   │   │   └── *.middleware.ts  # HTTP middleware (logging)
│   │   ├── services/
│   │   │   └── *.service.ts     # Application services (auth, profile, logger)
│   │   ├── profile/
│   │   │   ├── command/         # Profile commands & handlers
│   │   │   │   ├── *.command.ts # Profile commands
│   │   │   │   └── handler/
│   │   │   │       └── *.handler.ts # Command handlers
│   │   │   ├── events/          # Profile domain events
│   │   │   │   └── *.event.ts   # Profile events
│   │   │   └── profile.module.ts # Profile module configuration
│   │   └── application.module.ts # Application module aggregator
│   ├── domain/                  # Domain Layer (Pure Business Logic)
│   │   ├── __test__/
│   │   │   └── *.spec.ts        # Domain layer tests
│   │   ├── aggregates/          # Domain aggregates
│   │   ├── entities/
│   │   │   ├── *.ts             # Pure domain entities (Auth, Profile)
│   │   │   └── enums/           # Domain enums
│   │   │       └── *.enum.ts    # Role enums, etc.
│   │   ├── interfaces/
│   │   │   └── repositories/    # Repository contracts defined by domain
│   │   │       └── *.interface.ts # Repository interfaces
│   │   └── services/
│   │       └── *.service.ts     # Pure business logic services
│   ├── infrastructure/          # Infrastructure Layer (External Concerns)
│   │   ├── database/
│   │   │   ├── database.module.ts    # Database configuration
│   │   │   └── database.providers.ts # Database providers
│   │   ├── health/
│   │   │   └── *.check.ts       # Health check configurations
│   │   ├── logger/
│   │   │   └── logger.module.ts # Global logger module
│   │   ├── models/
│   │   │   ├── *.model.ts       # MongoDB models (auth, profile)
│   │   │   └── index.ts         # Model exports
│   │   └── repository/
│   │       └── *.repository.ts  # Repository implementations
│   ├── main.ts                  # Application entry point
│   ├── app.module.ts           # Root application module
│   └── constants.ts            # Application constants
├── test/
│   ├── *.e2e-spec.ts           # End-to-end tests
│   ├── jest-e2e.json           # E2E test configuration
│   └── setup-e2e.ts            # E2E test setup
├── prometheus/
│   └── prometheus.yml          # Prometheus configuration
├── docker-compose*.yml         # Docker Compose configurations (dev, prod)
└── Dockerfile                  # Container definition

🏗️ Architecture Overview

Layer Architecture

This project follows a strict 4-layer architecture:

  1. API Layer (src/api/): HTTP controllers, DTOs, and request/response handling
  2. Application Layer (src/application/): Business orchestration, CQRS coordination, and application services
  3. Domain Layer (src/domain/): Pure business logic, entities, and domain services
  4. Infrastructure Layer (src/infrastructure/): Database, external services, and technical implementations

Module Structure

  • ApiModule: Aggregates all HTTP controllers and imports ApplicationModule
  • ApplicationModule: Central orchestrator that imports and exports feature modules
  • AuthModule: Self-contained authentication feature with all its dependencies
  • ProfileModule: Self-contained profile management feature with all its dependencies
  • LoggerModule: Global infrastructure service for application-wide logging

CQRS Implementation

  • Commands: Handle write operations (Create, Update, Delete). Located in src/application/*/command.
  • Queries: Handle read operations (Find, Get). Located in src/application/*/query.
  • Handlers: Process commands and queries separately with proper business-context logging.
  • Events: Publish domain events for side effects and inter-module communication.

Event-Driven Flow

  1. User Registration:

API Controller → Application Service → Domain Service (validation) → RegisterCommand → CreateAuthUser → AuthUserCreated Event → RegistrationSaga → CreateProfile → ProfileCreated

  1. Authentication:

API Controller → Application Service → Domain Service (email validation) → LoginCommand → ValidateUser → JWT Token Generation

  1. Google OAuth Flow:

/auth/google → Google OAuth → /auth/google/redirect → Domain Service (validation) → FindOrCreateUser → JWT Token Generation

  1. Error Handling: ProfileCreationFailed Event → RegistrationSaga → DeleteAuthUser (Compensating Transaction)

Dependency Injection & Module Boundaries

  • Feature Modules: Each feature (Auth, Profile) manages its own dependencies
  • Domain Services: Injected via factories to maintain Clean Architecture principles
  • Repository Pattern: Interfaces defined in domain, implementations in infrastructure
  • Global Services: Logger provided globally via @Global() decorator

📋 Prerequisites

  • Node.js 20+
  • Docker and Docker Compose
  • MongoDB (included in Docker Compose)
  • Google OAuth2 credentials (for Google login functionality)

🐳 Running with Docker Compose

The project is configured to run seamlessly with Docker. Use the pnpm scripts from package.json for convenience.

# Build and start containers in detached mode for development
$ pnpm run docker:dev

# Build and start containers for production
$ pnpm run docker:prod

# View logs for the API service
$ pnpm run docker:logs

# Stop all running containers
$ pnpm run docker:down

# Restart the development environment
$ pnpm run docker:restart

🌐 Service Access

  • Application: http://localhost:4000
  • API Documentation (Swagger): http://localhost:4000/api
  • MongoDB: localhost:27017
  • Prometheus: http://localhost:9090
  • Grafana: http://localhost:3000 (admin/admin)

📦 Installation

$ pnpm install

🚀 Running the Application

# Development
$ pnpm run start

# Watch mode (recommended for development)
$ pnpm run start:dev

# Production mode
$ pnpm run start:prod

# Debug mode
$ pnpm run start:debug

🧪 Testing

# Unit tests
$ pnpm run test

# E2E tests
$ pnpm run test:e2e

# Test coverage
$ pnpm run test:cov

# Watch mode
$ pnpm run test:watch

🧹 Linting

# Check code style
$ pnpm run lint

# Auto-fix issues where possible
$ pnpm run lint:fix

🧪 API Testing

You can import this Postman collection to test the API endpoints.

The collection includes:

  • Authentication endpoints: Register, login, logout, Google OAuth
  • Profile management: Create, read, update profile data
  • Protected routes: Examples with JWT token authentication
  • Admin endpoints: Role-based access control examples
  • Environment variables: Pre-configured for localhost development

Using the Postman Collection

  1. Import the collection: Download and import NestJS CA-DDD.postman_collection.json into Postman
  2. Set environment variables: Configure the following variables in Postman:
  3. localhost: http://localhost (or your host)
  4. port: 4000 (or your configured port)
  5. Authorization: Bearer <your-jwt-token> (set after login)
  6. Test the flow:
  7. Start with user registration
  8. Login to get JWT token
  9. Use the token for protected endpoints

🔐 API Endpoints

Authentication

POST /auth/register       # User registration
POST /auth/login          # User login
POST /auth/logout         # User logout (Protected)
POST /auth/refresh-token  # Token refresh (Protected)
GET  /auth/google         # Initiate Google OAuth login
GET  /auth/google/redirect # Google OAuth callback
GET  /auth/:id            # Get user by auth ID (Protected)
DELETE /auth/:id          # Delete user by auth ID (Protected)

Profile Management (Protected)

```http GET /profile/all # Get all user profiles (Admin only) GET /profile/admins # Get all admin users (Admin only) GET /p

Extension points exported contracts — how you extend this code

IProfileRepository (Interface)
(no doc) [2 implementers]
src/domain/interfaces/repositories/profile-repository.interface.ts
ApiResponse (Interface)
(no doc) [1 implementers]
src/api/dto/common/api-response.dto.ts
Profile (Interface)
(no doc)
src/infrastructure/models/profile.model.ts
JwtPayload (Interface)
(no doc)
src/application/interfaces/authenticated-request.interface.ts
IAuthRepository (Interface)
(no doc) [2 implementers]
src/domain/interfaces/repositories/auth-repository.interface.ts
Auth (Interface)
(no doc)
src/infrastructure/models/auth.model.ts
AuthenticatedRequest (Interface)
(no doc)
src/application/interfaces/authenticated-request.interface.ts

Core symbols most depended-on inside this repo

logger
called by 29
src/application/services/logger.service.ts
success
called by 18
src/application/services/response.service.ts
findById
called by 12
src/domain/interfaces/repositories/auth-repository.interface.ts
update
called by 12
src/domain/interfaces/repositories/auth-repository.interface.ts
create
called by 10
src/domain/interfaces/repositories/auth-repository.interface.ts
error
called by 10
src/application/services/response.service.ts
get
called by 10
src/api/controllers/hello.controller.ts
findByAuthId
called by 9
src/domain/interfaces/repositories/profile-repository.interface.ts

Shape

Method 147
Class 106
Function 9
Interface 7
Enum 1

Languages

TypeScript100%

Modules by API surface

src/application/services/response.service.ts16 symbols
src/domain/services/auth-domain.service.ts15 symbols
src/application/services/auth.service.ts15 symbols
src/domain/services/profile-domain.service.ts13 symbols
src/api/dto/common/api-response.dto.ts12 symbols
src/api/controllers/auth.controller.ts12 symbols
src/infrastructure/repository/profile.repository.ts10 symbols
src/infrastructure/repository/auth.repository.ts10 symbols
src/application/services/profile.service.ts9 symbols
src/domain/interfaces/repositories/profile-repository.interface.ts8 symbols
src/domain/interfaces/repositories/auth-repository.interface.ts8 symbols
src/api/controllers/profile.controller.ts8 symbols

Datastores touched

(mongodb)Database · 1 repos
nestjsDatabase · 1 repos
nestjs-testDatabase · 1 repos

For agents

$ claude mcp add nestjs-clean-architecture \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page