We use class-transformer to easily convert plain data into class objects and back. This helps keep data organized and safe in NestJS apps.
0
0
class-transformer usage in NestJS
Introduction
When receiving JSON data from a user and you want to turn it into a class instance.
When sending data back to the user and you want to control which properties are shown.
When you want to automatically convert nested objects into class instances.
When you want to apply simple transformations like changing date strings into Date objects.
When you want to exclude sensitive fields like passwords from API responses.
Syntax
NestJS
import { plainToInstance, instanceToPlain } from 'class-transformer'; const classObject = plainToInstance(ClassName, plainObject); const plainObject = instanceToPlain(classObject);
plainToInstance converts plain objects to class instances.
instanceToPlain converts class instances back to plain objects.
Examples
This converts a simple object into a
User class instance.NestJS
import { plainToInstance } from 'class-transformer'; class User { id: number; name: string; } const plainUser = { id: 1, name: 'Alice' }; const user = plainToInstance(User, plainUser);
This hides the
password field when converting to JSON.NestJS
import { Exclude, Expose, plainToInstance, instanceToPlain } from 'class-transformer'; class User { id: number; @Exclude() password: string; @Expose() name: string; } const plainUser = { id: 1, name: 'Alice', password: 'secret' }; const user = plainToInstance(User, plainUser); const output = JSON.stringify(instanceToPlain(user));
Sample Program
This example shows how to convert plain data into a class instance and then back to a plain object while excluding the password field.
NestJS
import { plainToInstance, instanceToPlain, Exclude, Expose } from 'class-transformer'; class User { id: number; @Expose() name: string; @Exclude() password: string; constructor(id: number, name: string, password: string) { this.id = id; this.name = name; this.password = password; } } // Plain data from a client const plainUser = { id: 1, name: 'Alice', password: 'mypassword' }; // Convert plain object to class instance const userInstance = plainToInstance(User, plainUser); // Convert class instance back to plain object (password excluded) const safeUser = instanceToPlain(userInstance); console.log('User instance:', userInstance); console.log('Safe user object:', safeUser);
OutputSuccess
Important Notes
Remember to use decorators like @Exclude() and @Expose() to control which fields appear in output.
Nested objects can also be transformed automatically if you use @Type(() => ClassName) decorator.
Always validate your data separately; class-transformer only converts data shapes.
Summary
class-transformer helps convert plain data to class objects and back.
Use decorators to include or exclude fields easily.
This keeps your data clean and safe in NestJS applications.