The ValidationPipe
Enable ValidationPipe globally to automatically validate incoming DTOs.
Syntax
app.useGlobalPipes(new ValidationPipe())The ValidationPipe automatically validates request bodies against your DTO classes. Register it once and every endpoint benefits.
Turning it on
In main.ts, call app.useGlobalPipes(new ValidationPipe()). From then on, any handler with a DTO parameter is validated using the rules declared on that DTO.
Useful options
whitelist: true- strip properties not in the DTO.forbidNonWhitelisted: true- reject requests that include unknown properties.transform: true- convert payloads into DTO class instances.
Example
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({ whitelist: true, transform: true }),
);
await app.listen(3000);
}
bootstrap();When to use it
- A developer enables the global ValidationPipe with whitelist:true so unknown fields in the request body are silently stripped before hitting the service.
- An API team sets forbidNonWhitelisted:true to return 400 when a client sends unexpected fields, preventing accidental property leakage.
- A backend engineer uses transform:true so query parameter strings like "42" are automatically coerced to numbers in the handler signature.
More examples
Register ValidationPipe globally
Registers ValidationPipe globally in main.ts so every request body against a DTO class is validated automatically.
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
await app.listen(3000);
}
bootstrap();Strict options: whitelist and forbid
Combines all three safety options: strip, reject, and coerce, providing the strictest default behavior for production APIs.
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // strip unknown properties
forbidNonWhitelisted: true, // 400 if unknown properties present
transform: true, // coerce to DTO type
}),
);ValidationPipe on single route
Applies ValidationPipe at the method level using @UsePipes, scoping it to a single endpoint instead of globally.
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common';
import { CreateOrderDto } from './dto/create-order.dto';
@Controller('orders')
export class OrdersController {
@Post()
@UsePipes(new ValidationPipe({ whitelist: true }))
create(@Body() dto: CreateOrderDto) {
return dto;
}
}
Discussion