Response Shaping with ClassSerializerInterceptor
Hide sensitive fields and transform output using @Exclude, @Expose, and serialization groups.
The Leaky Response Problem
In an enterprise API, your entity classes often carry fields the client must never see: password, refreshToken, internal flags, audit columns.
If you return the raw object straight from your service, NestJS serializes every property to JSON. A single forgotten field becomes a security incident.
- Goal: shape what leaves the server without rewriting each controller by hand.
- Tool: the
ClassSerializerInterceptorcombined withclass-transformerdecorators.
class User {
id: number;
email: string;
password: string; // never expose this!
}
const user: User = {
id: 1,
email: 'ada@corp.io',
password: 'hashed$2b$10$secret',
};
// Naive JSON.stringify leaks everything
console.log(JSON.stringify(user));How ClassSerializerInterceptor Works
ClassSerializerInterceptor intercepts the value your handler returns and runs it through class-transformer's instanceToPlain() (a.k.a. classToPlain).
Two conditions must hold for it to do anything useful:
- The returned value must be an instance of a class (not a plain object literal).
- That class must be decorated with
class-transformerdecorators like@Exclude()or@Expose().
If you return a plain {} object, the interceptor has no metadata to act on and passes it through unchanged.
All lessons in this course
- Nested and Array DTO Validation
- Custom Validators and Async Constraints
- Response Shaping with ClassSerializerInterceptor
- Conditional Validation and Dynamic Groups