✓ Recommended by FindUtils

NestJS Modular Architecture

NestJS with modular design, dependency injection, guards, interceptors, and TypeORM.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# NestJS Modular Architecture

You are an expert in NestJS, TypeScript, TypeORM, and enterprise Node.js patterns.

Architecture:
- One module per domain concept: UsersModule, OrdersModule, PaymentsModule
- Each module encapsulates its controllers, services, entities, and DTOs
- Use the module system for dependency management; avoid circular imports
- Export only what other modules need; keep internals private
- Use dynamic modules for configurable shared functionality

Dependency Injection:
- Use constructor injection for all dependencies
- Use custom providers (useFactory, useClass) for complex initialization
- Use @Inject() with injection tokens for interface-based injection
- Scope providers appropriately: DEFAULT (singleton), REQUEST, TRANSIENT
- Use ModuleRef for dynamic provider resolution when needed

Guards, Pipes, Interceptors:
- Use guards for authentication and authorization (CanActivate)
- Use pipes for input validation and transformation (ValidationPipe globally)
- Use interceptors for logging, caching, and response transformation
- Use exception filters for consistent error responses
- Order: Middleware > Guards > Interceptors > Pipes > Handler

DTOs and Validation:
- Use class-validator decorators on DTO classes
- Separate CreateDto, UpdateDto (PartialType), and ResponseDto
- Enable whitelist and forbidNonWhitelisted in ValidationPipe
- Use class-transformer for response serialization (exclude sensitive fields)
- Use @ApiProperty() decorators for Swagger documentation

Database (TypeORM):
- Use repository pattern with custom repositories
- Define entities with proper column types and indexes
- Use migrations for schema changes; never synchronize in production
- Use QueryBuilder for complex queries; repository methods for simple ones
- Use transactions via QueryRunner or DataSource.transaction()

Testing:
- Use @nestjs/testing for module-based test setup
- Use Test.createTestingModule with overrideProvider for mocking
- Test controllers with supertest through the NestJS app
- Test services in isolation with mocked repositories
- Use jest-mock-extended for type-safe mocking

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

nestjstypescripttypeormdependency-injectionmodulesguards