📖 Scenario: You are building a simple NestJS application to manage user profiles. You want to ensure that the data sent to your API follows a strict format to avoid errors and keep your app reliable.
🎯 Goal: Build a DTO (Data Transfer Object) in NestJS that enforces a data contract for creating a user profile. This will help your API accept only the correct data shape and types.
📋 What You'll Learn
Create a DTO class with exact properties and types
Add validation decorators to enforce data rules
Use the DTO in a controller method parameter
Ensure the controller method accepts only valid data matching the DTO
💡 Why This Matters
🌍 Real World
APIs need to accept only correct and safe data to avoid bugs and security issues. DTOs help by defining clear data contracts.
💼 Career
Understanding DTOs and validation is essential for backend developers working with NestJS or similar frameworks to build reliable and maintainable APIs.
Progress0 / 4 steps
1
Create the UserProfileDto class
Create a class called UserProfileDto with these exact properties: username as a string, age as a number, and email as a string.
NestJS
Hint
Think of this class as a form that defines exactly what information a user profile must have.
2
Add validation decorators to UserProfileDto
Import IsString and IsInt from class-validator. Add @IsString() to username and email, and @IsInt() to age in the UserProfileDto class.
NestJS
Hint
These decorators check that the data matches the expected type before your app uses it.
3
Use UserProfileDto in a controller method
Create a controller class called UserController with a method createUser that takes a parameter userData of type UserProfileDto. Use the @Body() decorator on userData.
NestJS
Hint
This method will only accept data that matches the UserProfileDto structure.
4
Enable validation pipe in main app
In your main application bootstrap function, import ValidationPipe from @nestjs/common and use app.useGlobalPipes(new ValidationPipe()) to enable automatic validation of DTOs.
NestJS
Hint
This step makes sure your app checks the data against the DTO rules automatically.
Practice
(1/5)
1. Why do we use DTOs (Data Transfer Objects) in NestJS applications?
easy
A. To speed up the application runtime
B. To handle user interface styling
C. To replace database models completely
D. To define clear data shapes and enforce data contracts
Solution
Step 1: Understand the purpose of DTOs
DTOs are used to define the shape and structure of data that travels through the application.
Step 2: Identify the main benefit in NestJS context
They enforce data contracts, meaning they ensure data is consistent and validated before use.
Final Answer:
To define clear data shapes and enforce data contracts -> Option D
Quick Check:
DTOs = enforce data contracts [OK]
Hint: DTOs define data shape and rules clearly [OK]
Common Mistakes:
Thinking DTOs speed up runtime
Confusing DTOs with UI styling
Assuming DTOs replace database models
2. Which of the following is the correct way to define a simple DTO class in NestJS using TypeScript?
easy
A. interface CreateUserDto { name: string; age: number; }
B. class CreateUserDto { name: string; age: number; }
C. function CreateUserDto() { return { name: string, age: number }; }
D. const CreateUserDto = { name: 'string', age: 'number' };
Solution
Step 1: Recall NestJS DTO syntax
DTOs are usually defined as classes with typed properties in TypeScript.
Step 2: Check each option's syntax
class CreateUserDto { name: string; age: number; } correctly defines a class with typed properties. function CreateUserDto() { return { name: string, age: number }; } is a function, not a class. interface CreateUserDto { name: string; age: number; } is an interface, which can't be used for runtime validation. const CreateUserDto = { name: 'string', age: 'number' }; is an object literal with string values, not types.
Final Answer:
class CreateUserDto { name: string; age: number; } -> Option B
Quick Check:
DTO = class with typed properties [OK]
Hint: DTOs are classes with typed properties in NestJS [OK]
Common Mistakes:
Using interfaces instead of classes for DTOs
Defining DTOs as plain objects
Using functions instead of classes
3. Given this DTO and controller snippet, what will happen if the incoming request body misses the email property?
5. You want to ensure that a DTO enforces that the password field is always a string with at least 8 characters. Which approach best enforces this contract in NestJS?
hard
A. Use class-validator decorators like @IsString() and @MinLength(8) on the password property
B. Manually check the password length inside the controller method
C. Define password: string in the DTO without decorators
D. Use a plain JavaScript object instead of a class for the DTO
Solution
Step 1: Understand validation decorators in NestJS
Using class-validator decorators on DTO properties enforces rules automatically during validation.
Step 2: Compare options for enforcing password rules
Use class-validator decorators like @IsString() and @MinLength(8) on the password property uses decorators to enforce string type and minimum length. Manually check the password length inside the controller method requires manual checks, which is less clean. Define password: string in the DTO without decorators lacks validation. Use a plain JavaScript object instead of a class for the DTO loses type safety and validation.
Final Answer:
Use class-validator decorators like @IsString() and @MinLength(8) on the password property -> Option A
Quick Check:
Validation decorators enforce data contracts best [OK]
Hint: Use validation decorators on DTO properties [OK]
Common Mistakes:
Relying on manual validation in controllers
Skipping decorators and trusting types only
Using plain objects instead of classes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.