Overview
Serialization allows you to transform entity data before sending responses. Use custom DTOs (Data Transfer Objects) to:- Hide sensitive fields
- Transform data formats
- Add computed properties
- Control response structure for different operations
Basic Usage
Define a response DTO and apply it to your controller:get-company-response.dto.ts
serialize.ts
companies.controller.ts
The
@Exclude() decorator from class-transformer hides fields from the response.Serialization Options
You can define different DTOs for each operation:Available Options
Response DTOs
Simple Response DTO
Control which fields are returned:get-note-response.dto.ts
Delete Response DTO
Customize delete responses:delete-device-response.dto.ts
returnDeleted option:
devices.controller.ts
Using class-transformer
Leverageclass-transformer decorators for advanced transformations:
Exclude Fields
Expose Fields
Transform Values
Conditional Serialization
Groups
Use groups with@CrudAuth() for role-based serialization:
user-response.dto.ts
users.controller.ts
Disabling Serialization
Disable serialization for specific operations:Global Serialization Settings
Disable serialization globally:main.ts
Nested Objects
Handle nested entities in responses:Complete Example
Here’s a full serialization setup:responses/get-user-response.dto.ts
responses/index.ts
users.controller.ts
Best Practices
1
Always Hide Sensitive Data
Use
@Exclude() for passwords, tokens, and other sensitive information.2
Use Swagger Decorators
Add
@ApiProperty() decorators to response DTOs for accurate API documentation.3
Reuse DTOs
Use the same DTO for similar operations (e.g.,
get and getMany) to maintain consistency.4
Validate DTOs
Even though these are response DTOs, adding validation decorators helps with type safety.
Related Resources
- Authentication - Use groups for role-based serialization
- Swagger - Document your response DTOs
- DTOs - Learn about request DTOs