NestJS Code Review
Overview
Provides structured code review for NestJS applications. Findings categorized by severity (Critical, Warning, Suggestion) with actionable recommendations. Delegates to nestjs-code-review-expert agent for deep analysis.
When to Use
- "review NestJS code", "NestJS code review", "check my NestJS controller/service"
- Before merging pull requests or after implementing new features
- Validating NestJS decorators, DI patterns, guard implementations
- Architecture validation for NestJS modules and providers
- Reviewing DTOs, pipes, interceptors, and database integration (TypeORM, Prisma, Drizzle)
Instructions
Identify Scope: Determine which NestJS files and modules are under review. Use glob and grep to discover controllers, services, modules, guards, interceptors, and pipes in the target area.
Analyze Module Structure: Verify proper module organization — each feature should have its own module with clearly defined imports, controllers, providers, and exports. Check for circular dependencies and proper module boundaries.
Review Dependency Injection: Validate that all injectable services use constructor injection. Check provider scoping (singleton, request, transient) matches the intended lifecycle. Ensure no direct instantiation bypasses the DI container.
Evaluate Controllers: Review HTTP method usage, route naming, status codes, request/response DTOs, validation pipes, and OpenAPI decorators. Confirm controllers are thin — business logic belongs in services.
Assess Services & Business Logic: Check that services encapsulate business logic properly. Verify error handling, transaction management, and proper separation from infrastructure concerns. Look for service methods that are too large or have too many responsibilities.
Check Security: Review guard implementations, authentication/authorization patterns, input validation with class-validator, and protection against common vulnerabilities (injection, XSS, CSRF).
Review Testing: Assess test coverage for controllers, services, guards, and pipes. Verify proper mocking strategies and that tests validate behavior, not implementation details.
Validate Findings (Required checkpoint): Before finalizing, verify each Critical and Warning finding has reproducible evidence (file path, line numbers, exact code snippet) and a concrete, actionable fix. Remove or downgrade findings that are style preferences, overly subjective, or lack concrete remediation.
Produce Review Report: Generate structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.
Examples
Example 1: Reviewing a Controller
// ❌ Bad: Fat controller with business logic and missing validation
@Controller('users')
export class UserController {
constructor(private readonly userRepo: Repository<User>) {}
@Post()
async create(@Body() body: any) {
const user = this.userRepo.create(body);
return this.userRepo.save(user);
}
}
// ✅ Good: Thin controller with proper DTOs, validation, and service delegation
@Controller('users')
@ApiTags('Users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post()
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'Create a new user' })
@ApiResponse({ status: 201, type: UserResponseDto })
async create(
@Body(ValidationPipe) createUserDto: CreateUserDto,
): Promise<UserResponseDto> {
return this.userService.create(createUserDto);
}
}
Example 2: Reviewing Dependency Injection
// ❌ Bad: Direct instantiation bypasses DI
@Injectable()
export class OrderService {
private readonly logger = new Logger();
private readonly emailService = new EmailService();
async createOrder(dto: CreateOrderDto) {
this.emailService.send(dto.email, 'Order created');
}
}
// ✅ Good: Proper constructor injection
@Injectable()
export class OrderService {
private readonly logger = new Logger(OrderService.name);
constructor(
private readonly orderRepository: OrderRepository,
private readonly emailService: EmailService,
) {}
async createOrder(dto: CreateOrderDto): Promise<Order> {
const order = await this.orderRepository.create(dto);
await this.emailService.send(dto.email, 'Order created');
return order;
}
}
Example 3: Reviewing Error Handling
// ❌ Bad: Generic error handling with information leakage
@Get(':id')
async findOne(@Param('id') id: string) {
try {
return await this.service.findOne(id);
} catch (error) {
throw new HttpException(error.message, 500);
}
}
// ✅ Good: Domain-specific exceptions with proper HTTP mapping
@Get(':id')
async findOne(@Param('id', ParseUUIDPipe) id: string): Promise<UserResponseDto> {
const user = await this.userService.findOne(id);
if (!user) {
throw new NotFoundException(`User with ID ${id} not found`);
}
return user;
}
Example 4: Reviewing Guard Implementation
// ❌ Bad: Authorization logic in controller
@Get('admin/dashboard')
async getDashboard(@Req() req: Request) {
if (req.user.role !== 'admin') {
throw new ForbiddenException();
}
return this.dashboardService.getData();
}
// ✅ Good: Guard-based authorization with decorator
@Get('admin/dashboard')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.ADMIN)
async getDashboard(): Promise<DashboardDto> {
return this.dashboardService.getData();
}
Example 5: Reviewing Module Organization
// ❌ Bad: Monolithic module with everything
@Module({
imports: [TypeOrmModule.forFeature([User, Order, Product, Review])],
controllers: [UserController, OrderController, ProductController],
providers: [UserService, OrderService, ProductService, ReviewService],
})
export class AppModule {}
// ✅ Good: Feature-based module organization
@Module({
imports: [UserModule, OrderModule, ProductModule],
})
export class AppModule {}
@Module({
imports: [TypeOrmModule.forFeature([User])],
controllers: [UserController],
providers: [UserService, UserRepository],
exports: [UserService],
})
export class UserModule {}
Review Output Format
Structure all code review findings as follows:
1. Summary
Brief overview with an overall quality score (1-10) and key observations.
2. Critical Issues (Must Fix)
Issues that could cause security vulnerabilities, data corruption, or production failures.
3. Warnings (Should Fix)
Issues that violate best practices, reduce maintainability, or could lead to bugs.
4. Suggestions (Consider Improving)
Improvements for code readability, performance, or developer experience.
5. Positive Observations
Well-implemented patterns and good practices to acknowledge and encourage.
6. Recommendations
Prioritized next steps with code examples for the most impactful improvements.
Best Practices
- Controllers should be thin — delegate all business logic to services
- Use DTOs with class-validator for all request/response payloads
- Apply
ParseUUIDPipe, ParseIntPipe, etc. for parameter validation
- Use domain-specific exception classes extending
HttpException
- Organize code into feature modules with clear boundaries and exports
- Prefer constructor injection — never use
new for injectable services
- Apply guards for authentication and authorization, not inline checks
- Use interceptors for cross-cutting concerns (logging, caching, transformation)
- Add OpenAPI decorators (
@ApiTags, @ApiOperation, @ApiResponse) to all endpoints
- Write unit tests for services and integration tests for controllers
Constraints and Warnings
- Do not enforce a single ORM — the codebase may use TypeORM, Prisma, Drizzle, or MikroORM
- Respect existing project conventions even if they differ from NestJS defaults
- Focus on high-confidence issues — avoid false positives on style preferences
- When reviewing microservices patterns, consider transport-layer specific constraints
- Do not suggest architectural rewrites unless critical issues warrant them
References
See the references/ directory for detailed review checklists and pattern documentation:
references/patterns.md — NestJS best practice patterns with examples
references/anti-patterns.md — Common NestJS anti-patterns to flag during review
references/checklist.md — Comprehensive review checklist organized by area
1---2name: nestjs-code-review3description: Provides comprehensive code review capability for NestJS applications, analyzing controllers, services, modules, guards, interceptors, pipes, dependency injection, and database integration patterns. Use when reviewing NestJS code changes, before merging pull requests, after implementing new features, or for architecture validation. Triggers on "review NestJS code", "NestJS code review", "check my NestJS controller/service".4---5
6# NestJS Code Review
7
8## Overview
9
10Provides structured code review for NestJS applications. Findings categorized by severity (Critical, Warning, Suggestion) with actionable recommendations. Delegates to `nestjs-code-review-expert` agent for deep analysis.
11
12## When to Use
13
14- "review NestJS code", "NestJS code review", "check my NestJS controller/service"
15- Before merging pull requests or after implementing new features
16- Validating NestJS decorators, DI patterns, guard implementations
17- Architecture validation for NestJS modules and providers
18- Reviewing DTOs, pipes, interceptors, and database integration (TypeORM, Prisma, Drizzle)
19
20## Instructions
21
221. **Identify Scope**: Determine which NestJS files and modules are under review. Use `glob` and `grep` to discover controllers, services, modules, guards, interceptors, and pipes in the target area.
23
242. **Analyze Module Structure**: Verify proper module organization — each feature should have its own module with clearly defined imports, controllers, providers, and exports. Check for circular dependencies and proper module boundaries.
25
263. **Review Dependency Injection**: Validate that all injectable services use constructor injection. Check provider scoping (singleton, request, transient) matches the intended lifecycle. Ensure no direct instantiation bypasses the DI container.
27
284. **Evaluate Controllers**: Review HTTP method usage, route naming, status codes, request/response DTOs, validation pipes, and OpenAPI decorators. Confirm controllers are thin — business logic belongs in services.
29
305. **Assess Services & Business Logic**: Check that services encapsulate business logic properly. Verify error handling, transaction management, and proper separation from infrastructure concerns. Look for service methods that are too large or have too many responsibilities.
31
326. **Check Security**: Review guard implementations, authentication/authorization patterns, input validation with class-validator, and protection against common vulnerabilities (injection, XSS, CSRF).
33
347. **Review Testing**: Assess test coverage for controllers, services, guards, and pipes. Verify proper mocking strategies and that tests validate behavior, not implementation details.
35
368. **Validate Findings** (Required checkpoint): Before finalizing, verify each Critical and Warning finding has reproducible evidence (file path, line numbers, exact code snippet) and a concrete, actionable fix. Remove or downgrade findings that are style preferences, overly subjective, or lack concrete remediation.
37
389. **Produce Review Report**: Generate structured report with severity-classified findings (Critical, Warning, Suggestion), positive observations, and prioritized recommendations with code examples.
39
40## Examples
41
42### Example 1: Reviewing a Controller
43
44```typescript
45// ❌ Bad: Fat controller with business logic and missing validation
46@Controller('users')
47export class UserController {
48 constructor(private readonly userRepo: Repository<User>) {}
49
50 @Post()
51 async create(@Body() body: any) {
52 const user = this.userRepo.create(body);
53 return this.userRepo.save(user);
54 }
55}
56
57// ✅ Good: Thin controller with proper DTOs, validation, and service delegation
58@Controller('users')
59@ApiTags('Users')
60export class UserController {
61 constructor(private readonly userService: UserService) {}
62
63 @Post()
64 @HttpCode(HttpStatus.CREATED)
65 @ApiOperation({ summary: 'Create a new user' })
66 @ApiResponse({ status: 201, type: UserResponseDto })
67 async create(
68 @Body(ValidationPipe) createUserDto: CreateUserDto,
69 ): Promise<UserResponseDto> {
70 return this.userService.create(createUserDto);
71 }
72}
73```
74
75### Example 2: Reviewing Dependency Injection
76
77```typescript
78// ❌ Bad: Direct instantiation bypasses DI
79@Injectable()
80export class OrderService {
81 private readonly logger = new Logger();
82 private readonly emailService = new EmailService();
83
84 async createOrder(dto: CreateOrderDto) {
85 this.emailService.send(dto.email, 'Order created');
86 }
87}
88
89// ✅ Good: Proper constructor injection
90@Injectable()
91export class OrderService {
92 private readonly logger = new Logger(OrderService.name);
93
94 constructor(
95 private readonly orderRepository: OrderRepository,
96 private readonly emailService: EmailService,
97 ) {}
98
99 async createOrder(dto: CreateOrderDto): Promise<Order> {
100 const order = await this.orderRepository.create(dto);
101 await this.emailService.send(dto.email, 'Order created');
102 return order;
103 }
104}
105```
106
107### Example 3: Reviewing Error Handling
108
109```typescript
110// ❌ Bad: Generic error handling with information leakage
111@Get(':id')
112async findOne(@Param('id') id: string) {
113 try {
114 return await this.service.findOne(id);
115 } catch (error) {
116 throw new HttpException(error.message, 500);
117 }
118}
119
120// ✅ Good: Domain-specific exceptions with proper HTTP mapping
121@Get(':id')
122async findOne(@Param('id', ParseUUIDPipe) id: string): Promise<UserResponseDto> {
123 const user = await this.userService.findOne(id);
124 if (!user) {
125 throw new NotFoundException(`User with ID ${id} not found`);
126 }
127 return user;
128}
129```
130
131### Example 4: Reviewing Guard Implementation
132
133```typescript
134// ❌ Bad: Authorization logic in controller
135@Get('admin/dashboard')
136async getDashboard(@Req() req: Request) {
137 if (req.user.role !== 'admin') {
138 throw new ForbiddenException();
139 }
140 return this.dashboardService.getData();
141}
142
143// ✅ Good: Guard-based authorization with decorator
144@Get('admin/dashboard')
145@UseGuards(JwtAuthGuard, RolesGuard)
146@Roles(Role.ADMIN)
147async getDashboard(): Promise<DashboardDto> {
148 return this.dashboardService.getData();
149}
150```
151
152### Example 5: Reviewing Module Organization
153
154```typescript
155// ❌ Bad: Monolithic module with everything
156@Module({
157 imports: [TypeOrmModule.forFeature([User, Order, Product, Review])],
158 controllers: [UserController, OrderController, ProductController],
159 providers: [UserService, OrderService, ProductService, ReviewService],
160})
161export class AppModule {}
162
163// ✅ Good: Feature-based module organization
164@Module({
165 imports: [UserModule, OrderModule, ProductModule],
166})
167export class AppModule {}
168
169@Module({
170 imports: [TypeOrmModule.forFeature([User])],
171 controllers: [UserController],
172 providers: [UserService, UserRepository],
173 exports: [UserService],
174})
175export class UserModule {}
176```
177
178## Review Output Format
179
180Structure all code review findings as follows:
181
182### 1. Summary
183Brief overview with an overall quality score (1-10) and key observations.
184
185### 2. Critical Issues (Must Fix)
186Issues that could cause security vulnerabilities, data corruption, or production failures.
187
188### 3. Warnings (Should Fix)
189Issues that violate best practices, reduce maintainability, or could lead to bugs.
190
191### 4. Suggestions (Consider Improving)
192Improvements for code readability, performance, or developer experience.
193
194### 5. Positive Observations
195Well-implemented patterns and good practices to acknowledge and encourage.
196
197### 6. Recommendations
198Prioritized next steps with code examples for the most impactful improvements.
199
200## Best Practices
201
202- Controllers should be thin — delegate all business logic to services
203- Use DTOs with class-validator for all request/response payloads
204- Apply `ParseUUIDPipe`, `ParseIntPipe`, etc. for parameter validation
205- Use domain-specific exception classes extending `HttpException`
206- Organize code into feature modules with clear boundaries and exports
207- Prefer constructor injection — never use `new` for injectable services
208- Apply guards for authentication and authorization, not inline checks
209- Use interceptors for cross-cutting concerns (logging, caching, transformation)
210- Add OpenAPI decorators (`@ApiTags`, `@ApiOperation`, `@ApiResponse`) to all endpoints
211- Write unit tests for services and integration tests for controllers
212
213## Constraints and Warnings
214
215- Do not enforce a single ORM — the codebase may use TypeORM, Prisma, Drizzle, or MikroORM
216- Respect existing project conventions even if they differ from NestJS defaults
217- Focus on high-confidence issues — avoid false positives on style preferences
218- When reviewing microservices patterns, consider transport-layer specific constraints
219- Do not suggest architectural rewrites unless critical issues warrant them
220
221## References
222
223See the `references/` directory for detailed review checklists and pattern documentation:
224- `references/patterns.md` — NestJS best practice patterns with examples
225- `references/anti-patterns.md` — Common NestJS anti-patterns to flag during review
226- `references/checklist.md` — Comprehensive review checklist organized by area