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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
rust
use axum::{
    extract::{Path, State},
    response::sse::{Event, KeepAlive, Sse},
};

Streaming import progress with SSE in Axum

server-sent-events streams watch-channel
Advanced 7 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps
typescript
import { useEffect, useState } from "react";
 
interface Section {
  id: string;

Building a scroll-spy hook in React

custom-hooks intersectionobserver dom-observation
Intermediate 8 steps

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