typescript 64 lines · 10 steps

Shaping API responses with class-transformer in NestJS

Decorators on an entity control exactly which fields reach the client when NestJS serializes the response.

Explained by highlit
1import { Exclude, Expose, Transform, Type } from 'class-transformer';
2 
3export class AddressEntity {
4 street: string;
5 city: string;
6 country: string;
7 
8 constructor(partial: Partial<AddressEntity>) {
9 Object.assign(this, partial);
10 }
11}
12 
13export class UserEntity {
14 id: string;
15 email: string;
16 firstName: string;
17 lastName: string;
18 
19 @Exclude()
20 password: string;
21 
22 @Exclude()
23 passwordResetToken: string | null;
24 
25 @Exclude({ toPlainOnly: true })
26 twoFactorSecret: string | null;
27 
28 @Expose()
29 get fullName(): string {
30 return `${this.firstName} ${this.lastName}`.trim();
31 }
32 
33 @Transform(({ value }) => value?.toISOString())
34 createdAt: Date;
35 
36 @Type(() => AddressEntity)
37 address: AddressEntity;
38 
39 @Expose({ groups: ['admin'] })
40 role: 'user' | 'admin';
41 
42 constructor(partial: Partial<UserEntity>) {
43 Object.assign(this, partial);
44 }
45}
46 
47@Controller('users')
48@UseInterceptors(ClassSerializerInterceptor)
49export class UsersController {
50 constructor(private readonly usersService: UsersService) {}
51 
52 @Get(':id')
53 async findOne(@Param('id') id: string): Promise<UserEntity> {
54 const user = await this.usersService.findById(id);
55 return new UserEntity(user);
56 }
57 
58 @Get()
59 @SerializeOptions({ groups: ['admin'] })
60 async findAll(): Promise<UserEntity[]> {
61 const users = await this.usersService.findAll();
62 return users.map((user) => new UserEntity(user));
63 }
64}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Declaring serialization rules on the entity keeps sensitive-field logic in one place instead of scattered across controllers.
  2. 2ClassSerializerInterceptor only transforms real class instances, so handlers must return `new Entity(...)`, not plain objects.
  3. 3Group-based exposure lets one entity serve different audiences by toggling SerializeOptions per route.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Shaping API responses with class-transformer in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code