0
0
NestJSframework~30 mins

Whitelist and transform options in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Whitelist and Transform Options in NestJS
📖 Scenario: You are building a simple NestJS API that accepts user data. To keep your API safe and clean, you want to only allow specific properties from the incoming data and automatically convert data types where needed.
🎯 Goal: Build a NestJS controller that uses ValidationPipe with whitelist and transform options enabled to accept only allowed properties and transform input data types.
📋 What You'll Learn
Create a DTO class CreateUserDto with properties name (string) and age (number)
Set up a controller UsersController with a POST route /users
Use ValidationPipe globally or on the route with whitelist: true and transform: true
Ensure that extra properties sent in the request body are removed and that age is transformed to a number
💡 Why This Matters
🌍 Real World
APIs often receive data from users or other systems. Using whitelist and transform options helps keep data clean and safe by removing unwanted fields and converting types automatically.
💼 Career
Understanding how to validate and sanitize input data is essential for backend developers working with NestJS or similar frameworks to build secure and reliable APIs.
Progress0 / 4 steps
1
Create the DTO class for user data
Create a class called CreateUserDto with two properties: name of type string and age of type number. Use decorators @IsString() for name and @IsNumber() for age from class-validator.
NestJS
Need a hint?

Use class-validator decorators to specify the types for validation.

2
Set up the UsersController with a POST route
Create a controller class called UsersController with a POST route /users. Add a method createUser that accepts a parameter createUserDto of type CreateUserDto decorated with @Body().
NestJS
Need a hint?

Use @Controller('users') and @Post() decorators to define the route.

3
Enable ValidationPipe with whitelist and transform options
In your main application bootstrap file, import ValidationPipe from @nestjs/common and apply it globally with options whitelist: true and transform: true using app.useGlobalPipes().
NestJS
Need a hint?

Use app.useGlobalPipes() with a new ValidationPipe instance and pass the options object.

4
Complete the setup by exporting the controller and DTO
Ensure that CreateUserDto and UsersController are exported properly from their files so they can be imported in the module.
NestJS
Need a hint?

Make sure the classes have the export keyword so they can be imported elsewhere.