It is best practice to validate the correctness of any data sent into a web application. To automatically validate incoming requests, Nest provides several pipes available right out-of-the-box:
ValidationPipe
ParseIntPipe
ParseBoolPipe
ParseArrayPipe
ParseUUIDPipe
main.ts
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
// error handling when failed to validate the body
exceptionFactory: (validationErrors: ValidationError[] = []) => {
const logger = app.get(Logger);
logger.error(JSON.stringify(validationErrors));
return new BadRequestException(validationErrors);
},
// transform into correct type based on type definition
transform: true,
// remove unlisted field
whitelist: true,
}),
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
The ValidationPipe makes use of the powerful package and its declarative validation decorators. The ValidationPipe provides a convenient approach to enforce validation rules for all incoming client payloads, where the specific rules are declared with simple annotations in local class/DTO declarations in each module.