0PricingLogin
NestJS Enterprise Backend APIs · Lesson

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 ClassSerializerInterceptor combined with class-transformer decorators.
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-transformer decorators 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

  1. Nested and Array DTO Validation
  2. Custom Validators and Async Constraints
  3. Response Shaping with ClassSerializerInterceptor
  4. Conditional Validation and Dynamic Groups
← Back to NestJS Enterprise Backend APIs