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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Declaring serialization rules on the entity keeps sensitive-field logic in one place instead of scattered across controllers.
- 2ClassSerializerInterceptor only transforms real class instances, so handlers must return `new Entity(...)`, not plain objects.
- 3Group-based exposure lets one entity serve different audiences by toggling SerializeOptions per route.
Related explainers
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/shaping-api-responses-with-class-transformer-in-nestjs-explained-typescript-1290/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.