intermediate
NestJS pipes
Use pipes for transformation and validation at the boundary, including DTO validation, coercion, and predictable error output.
Pipes transform or validate input before it reaches the handler. `ValidationPipe` with class-validator DTOs is the standard boundary for HTTP bodies and query params.
export class CreateUserDto {
@IsEmail()
email: string;
@IsInt()
@Min(18)
age: number;
}
@Post()
create(@Body(new ValidationPipe({ whitelist: true })) dto: CreateUserDto) {
return this.users.create(dto);
}
Built-in pipes: `ParseIntPipe`, `ParseUUIDPipe`, `DefaultValuePipe`. Global `ValidationPipe` in `main.ts` enforces `whitelist` and `forbidNonWhitelisted` app-wide. Pipes throw `BadRequestException` on failure — filters shape the response.
On interviews: pipes versus manual validation, `transform: true` for coercion, and why DTO classes beat plain interfaces at runtime.
Common pitfalls: interfaces instead of classes (no runtime metadata), missing whitelist allowing mass assignment, and validation only on body but not params.
The trade-off is balancing simplicity, performance, safety, and operability — name which axis you optimized and what cost you accepted.
Checklist:
- Use ValidationPipe with class-validator DTOs.
- Enable whitelist and forbid unknown properties.
- Apply Parse* pipes to route and query params.
- Register a global ValidationPipe for consistency.