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