NestJS 11 Best Practices
Quick Reference
| Topic |
When to Use |
Reference |
| Core Architecture |
Modules, Providers, DI, forwardRef, custom decorators |
core-architecture.md |
| Request Lifecycle |
Middleware, Guards, Interceptors, Pipes, Filters |
request-lifecycle.md |
| Validation & Pipes |
DTOs, class-validator, ValidationPipe, transforms |
validation-pipes.md |
| Authentication |
JWT, Passport, Guards, Local/OAuth strategies, RBAC |
authentication.md |
| Database |
TypeORM, Prisma, Drizzle ORM, repository patterns |
database-integration.md |
| Testing |
Unit tests, E2E tests, mocking providers |
testing.md |
| OpenAPI & GraphQL |
Swagger decorators, resolvers, subscriptions |
openapi-graphql.md |
| Microservices |
TCP, Redis, NATS, Kafka patterns |
microservices.md |
Essential Patterns
Module with Providers
@Module({
imports: [DatabaseModule],
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // Export for other modules
})
export class UsersModule {}
Controller with Validation
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return this.usersService.create(createUserDto);
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.usersService.findOne(id);
}
}
DTO with Validation
import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(8)
password: string;
@IsOptional()
@IsString()
name?: string;
}
Exception Filter
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
response.status(status).json({
statusCode: status,
message: exception.message,
timestamp: new Date().toISOString(),
});
}
}
Guard with JWT
@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
canActivate(context: ExecutionContext) {
return super.canActivate(context);
}
}
NestJS 11 Breaking Changes
- Express v5: Wildcards must be named (e.g.,
*splat), optional params use braces /:file{.:ext}
- Node.js 20+: Minimum required version
- Fastify v5: Updated adapter for Fastify users
- Dynamic Modules: Same module with identical config imported multiple times = separate instances
Common Mistakes
- Not using
forwardRef() for circular deps - Causes "cannot resolve dependency" errors; wrap in forwardRef(() => ModuleName)
- Throwing plain errors instead of HttpException - Loses status codes, breaks exception filters; use
throw new BadRequestException('message')
- Missing
@Injectable() decorator - Provider won't be injectable; always decorate services
- Global ValidationPipe without
whitelist: true - Allows unexpected properties; set whitelist: true, forbidNonWhitelisted: true
- Importing modules instead of exporting providers - Use
exports array to share providers across modules
- Async config without
ConfigModule.forRoot() - ConfigService undefined; import ConfigModule in AppModule
- Testing without
overrideProvider() - Uses real services in unit tests; mock dependencies with overrideProvider(Service).useValue(mock)
- E2E tests sharing database state - No isolation between tests; use transactions or truncate tables in beforeEach
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: ejirocodes-agent-skills-nestjs-best-practices3description: NestJS 11 Best Practices4---56# NestJS 11 Best Practices78## Quick Reference910| Topic | When to Use | Reference |11|-------|-------------|-----------|12| **Core Architecture** | Modules, Providers, DI, forwardRef, custom decorators | [core-architecture.md](references/core-architecture.md) |13| **Request Lifecycle** | Middleware, Guards, Interceptors, Pipes, Filters | [request-lifecycle.md](references/request-lifecycle.md) |14| **Validation & Pipes** | DTOs, class-validator, ValidationPipe, transforms | [validation-pipes.md](references/validation-pipes.md) |15| **Authentication** | JWT, Passport, Guards, Local/OAuth strategies, RBAC | [authentication.md](references/authentication.md) |16| **Database** | TypeORM, Prisma, Drizzle ORM, repository patterns | [database-integration.md](references/database-integration.md) |17| **Testing** | Unit tests, E2E tests, mocking providers | [testing.md](references/testing.md) |18| **OpenAPI & GraphQL** | Swagger decorators, resolvers, subscriptions | [openapi-graphql.md](references/openapi-graphql.md) |19| **Microservices** | TCP, Redis, NATS, Kafka patterns | [microservices.md](references/microservices.md) |2021## Essential Patterns2223### Module with Providers2425```typescript26@Module({27 imports: [DatabaseModule],28 controllers: [UsersController],29 providers: [UsersService],30 exports: [UsersService], // Export for other modules31})32export class UsersModule {}33```3435### Controller with Validation3637```typescript38@Controller('users')39export class UsersController {40 constructor(private readonly usersService: UsersService) {}4142 @Post()43 create(@Body() createUserDto: CreateUserDto) {44 return this.usersService.create(createUserDto);45 }4647 @Get(':id')48 findOne(@Param('id', ParseIntPipe) id: number) {49 return this.usersService.findOne(id);50 }51}52```5354### DTO with Validation5556```typescript57import { IsEmail, IsString, MinLength, IsOptional } from 'class-validator';5859export class CreateUserDto {60 @IsEmail()61 email: string;6263 @IsString()64 @MinLength(8)65 password: string;6667 @IsOptional()68 @IsString()69 name?: string;70}71```7273### Exception Filter7475```typescript76@Catch(HttpException)77export class HttpExceptionFilter implements ExceptionFilter {78 catch(exception: HttpException, host: ArgumentsHost) {79 const ctx = host.switchToHttp();80 const response = ctx.getResponse<Response>();81 const status = exception.getStatus();8283 response.status(status).json({84 statusCode: status,85 message: exception.message,86 timestamp: new Date().toISOString(),87 });88 }89}90```9192### Guard with JWT9394```typescript95@Injectable()96export class JwtAuthGuard extends AuthGuard('jwt') {97 canActivate(context: ExecutionContext) {98 return super.canActivate(context);99 }100}101```102103## NestJS 11 Breaking Changes104105- **Express v5**: Wildcards must be named (e.g., `*splat`), optional params use braces `/:file{.:ext}`106- **Node.js 20+**: Minimum required version107- **Fastify v5**: Updated adapter for Fastify users108- **Dynamic Modules**: Same module with identical config imported multiple times = separate instances109110## Common Mistakes1111121. **Not using `forwardRef()` for circular deps** - Causes "cannot resolve dependency" errors; wrap in `forwardRef(() => ModuleName)`1132. **Throwing plain errors instead of HttpException** - Loses status codes, breaks exception filters; use `throw new BadRequestException('message')`1143. **Missing `@Injectable()` decorator** - Provider won't be injectable; always decorate services1154. **Global ValidationPipe without `whitelist: true`** - Allows unexpected properties; set `whitelist: true, forbidNonWhitelisted: true`1165. **Importing modules instead of exporting providers** - Use `exports` array to share providers across modules1176. **Async config without `ConfigModule.forRoot()`** - ConfigService undefined; import ConfigModule in AppModule1187. **Testing without `overrideProvider()`** - Uses real services in unit tests; mock dependencies with `overrideProvider(Service).useValue(mock)`1198. **E2E tests sharing database state** - No isolation between tests; use transactions or truncate tables in beforeEach120121---122> Converted and distributed by [TomeVault](https://tomevault.io/claim/ejirocodes) — claim your Tome and manage your conversions.123<!-- tomevault:4.0:skill_md:2026-04-11 -->