Whitelist and transform options help clean and shape data coming into your NestJS app. They make sure only allowed data is kept and convert data to the right types automatically.
Whitelist and transform options in NestJS
import { ValidationPipe } from '@nestjs/common'; app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true, }));
whitelist: Removes any properties that are not in your DTO (Data Transfer Object).
transform: Automatically converts input data to the types defined in your DTO classes.
new ValidationPipe({ whitelist: true })new ValidationPipe({ transform: true })new ValidationPipe({ whitelist: true, transform: true })new ValidationPipe({ whitelist: false, transform: false })This NestJS app has a POST /users endpoint. It uses ValidationPipe with whitelist and transform options on the body. It only accepts 'name' and 'age' fields. It converts 'age' to a number automatically.
If extra fields are sent, they are removed. If 'age' is sent as a string like '25', it becomes the number 25.
import { Controller, Post, Body, ValidationPipe } from '@nestjs/common'; import { IsInt, IsString } from 'class-validator'; import { NestFactory } from '@nestjs/core'; import { Module } from '@nestjs/common'; class CreateUserDto { @IsString() name: string; @IsInt() age: number; } @Controller('users') class UserController { @Post() createUser(@Body(new ValidationPipe({ whitelist: true, transform: true })) createUserDto: CreateUserDto) { return createUserDto; } } @Module({ controllers: [UserController], }) class AppModule {} async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
Time complexity: Validation and transformation run in linear time relative to input size.
Space complexity: Uses extra memory proportional to input size for creating new objects.
Common mistake: Forgetting to enable whitelist allows unwanted fields to pass through.
Use whitelist to keep data clean and transform to avoid manual type conversions.
Whitelist removes unwanted fields from input data.
Transform converts input data to the types defined in your DTO.
Using both together keeps your app safe and your data clean.