How to Use class-transformer in NestJS for Object Transformation
In NestJS, use
class-transformer to convert plain JavaScript objects into class instances and apply transformations using decorators like @Expose() and @Type(). Integrate it by installing the package, importing it, and using plainToInstance() or enabling it globally with pipes for automatic transformation.Syntax
The main functions and decorators from class-transformer used in NestJS are:
plainToInstance(Class, plainObject): Converts a plain object to an instance of a class.@Expose(): Marks properties to include during transformation.@Exclude(): Marks properties to exclude during transformation.@Type(() => Class): Specifies the type of nested objects for proper transformation.
These help control how data is transformed and serialized in your NestJS app.
typescript
import { plainToInstance } from 'class-transformer'; import { Expose, Exclude, Type } from 'class-transformer'; class UserDto { @Expose() id: number; @Expose() name: string; @Exclude() password: string; @Type(() => Date) @Expose() createdAt: Date; } const plainUser = { id: 1, name: 'Alice', password: 'secret', createdAt: '2024-06-01T12:00:00Z' }; const user = plainToInstance(UserDto, plainUser); console.log(user);
Output
UserDto { id: 1, name: 'Alice', createdAt: 2024-06-01T12:00:00.000Z }
Example
This example shows how to use class-transformer in a NestJS controller to automatically transform incoming JSON into a typed class instance and exclude sensitive fields when returning data.
typescript
import { Controller, Post, Body } from '@nestjs/common'; import { plainToInstance, Expose, Exclude } from 'class-transformer'; class CreateUserDto { @Expose() username: string; @Expose() email: string; @Exclude() password: string; } @Controller('users') export class UsersController { @Post() create(@Body() body: any) { const user = plainToInstance(CreateUserDto, body); // password is excluded from the transformed instance return user; } }
Output
{"username":"john_doe","email":"john@example.com"}
Common Pitfalls
Common mistakes when using class-transformer in NestJS include:
- Not enabling transformation globally or manually, so plain objects are not converted to class instances.
- Forgetting to use
@Expose()or@Exclude(), which can cause unexpected properties to appear or sensitive data to leak. - Not using
@Type()for nested objects, resulting in nested data staying as plain objects instead of class instances. - Using
class-transformerwithout installing the package or importing it correctly.
Example of a wrong and right way:
typescript
/* Wrong: No transformation, password exposed */ class User { id: number; name: string; password: string; } const user = { id: 1, name: 'Bob', password: '1234' }; console.log(user); // password visible /* Right: Use @Exclude and plainToInstance */ import { Exclude, plainToInstance } from 'class-transformer'; class UserSafe { id: number; name: string; @Exclude() password: string; } const safeUser = plainToInstance(UserSafe, user); console.log(safeUser); // password hidden
Output
{ id: 1, name: 'Bob', password: '1234' }
UserSafe { id: 1, name: 'Bob' }
Quick Reference
| Feature | Description | Usage |
|---|---|---|
| plainToInstance | Convert plain object to class instance | plainToInstance(Class, plainObject) |
| @Expose() | Include property in transformation | @Expose() above property |
| @Exclude() | Exclude property from transformation | @Exclude() above property |
| @Type() | Specify type for nested objects | @Type(() => Class) |
| Enable global transform | Automatically transform request bodies | Use ValidationPipe with transform: true |
Key Takeaways
Use plainToInstance() to convert plain objects to class instances in NestJS.
Decorate properties with @Expose() and @Exclude() to control serialization.
Use @Type() for nested object transformation to maintain types.
Enable global transformation in NestJS pipes for automatic conversion.
Always install and import class-transformer to avoid runtime errors.