NestJS Class Transformer
Class Transformer is an npm package that converts plain JavaScript objects into class instances and back. In NestJS, it works alongside Class Validator and the ValidationPipe to transform incoming request data and outgoing response data. It lets you control exactly which fields serialize, how types convert, and what sensitive data gets excluded from responses.
Why Class Transformer Is Needed
When a request body arrives at your NestJS application, it is a plain JavaScript object — it has no class methods and no type information attached. For Class Validator decorators to run, the object must first become a real class instance. Class Transformer performs this conversion automatically when you enable it inside the ValidationPipe.
Plain object (from JSON body):
{ name: 'Alice', age: '30' }
After Class Transformer runs:
new CreateUserDto() instance with name = 'Alice', age = 30 (number)
Enabling Class Transformer
Class Transformer activates when you set transform: true in the global ValidationPipe:
app.useGlobalPipes(new ValidationPipe({
transform: true, // ← enables class-transformer
whitelist: true,
}));
With transform: true, NestJS converts every incoming body to a proper class instance using the DTO type declared on the controller parameter. You also need to install the package:
npm install class-transformer
Type Conversion
The most practical benefit of Class Transformer is automatic type conversion. Query string values and route parameters always arrive as strings. Declaring the correct type in your DTO and enabling transform causes Class Transformer to convert the value automatically:
export class CreateProductDto {
@IsString()
name: string;
@IsNumber()
price: number; // declared as number
@IsBoolean()
inStock: boolean; // declared as boolean
}
// Client sends: { "name": "Laptop", "price": "999", "inStock": "true" }
// After transform: { name: 'Laptop', price: 999, inStock: true }
"999" becomes 999. "true" becomes true. Your service receives properly typed data with no manual conversion code in the controller.
Excluding Properties from Responses
Class Transformer's most powerful feature for responses is the @Exclude() decorator. Apply it to properties you never want to expose to clients — like passwords, internal IDs, or secret tokens:
import { Exclude } from 'class-transformer';
export class UserEntity {
id: number;
name: string;
email: string;
@Exclude()
password: string; // never sent in responses
@Exclude()
refreshToken: string;
}
For this exclusion to work in responses, activate the ClassSerializerInterceptor globally in main.ts:
import { ClassSerializerInterceptor } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)));
Now any response that returns a UserEntity instance automatically strips the password and refreshToken fields before sending data to the client.
Exposing Only Specific Properties
The opposite approach uses @Expose() and the excludeExtraneousValues option to send only explicitly marked fields:
import { Expose } from 'class-transformer';
export class UserResponseDto {
@Expose()
id: number;
@Expose()
name: string;
@Expose()
email: string;
// password is not decorated with @Expose() → excluded automatically
}
// In service, convert entity to response DTO
import { plainToInstance } from 'class-transformer';
const responseDto = plainToInstance(UserResponseDto, userEntity, {
excludeExtraneousValues: true,
});
Transforming Values with @Transform
The @Transform() decorator runs a custom function during transformation — useful for formatting dates, rounding numbers, or converting data structures:
import { Transform } from 'class-transformer';
export class UserDto {
@Transform(({ value }) => value.toLowerCase())
email: string; // always converted to lowercase
@Transform(({ value }) => new Date(value).toISOString())
createdAt: string; // converts date to ISO string format
}
plainToInstance and instanceToPlain
Class Transformer provides two core functions for manual conversion:
import { plainToInstance, instanceToPlain } from 'class-transformer';
// Convert plain object to class instance (request processing)
const dto = plainToInstance(CreateUserDto, { name: 'Alice', age: '30' });
// dto is now a CreateUserDto instance with age converted to number
// Convert class instance to plain object (response processing)
const plain = instanceToPlain(userEntity);
// plain is a plain object with @Exclude() fields removed
Transformation Flow
Incoming Request Outgoing Response
| |
v |
plainToInstance(DTO, body) instanceToPlain(entity)
| |
v |
Class instance with types Plain object with excluded fields removed
| |
v v
ValidationPipe checks Response sent to client
decorators (no passwords, no secrets)
Class Transformer handles both ends of the data pipeline: it shapes incoming data into properly typed class instances before validation runs, and it sanitizes outgoing data by stripping sensitive fields before they reach the client. Together with Class Validator and the ValidationPipe, it completes the data validation and transformation layer that every production NestJS API needs.
