A NestJS 12 app binds ClassSerializerInterceptor globally and marks UserEntity.password with @Exclude(), yet one endpoint still returns the password; why?
answer
- decorators live on the class
- a spread drops the prototype
- @Res() skips the stream
- @SerializeOptions type converts first
basics
~20 sClassSerializerInterceptor applies class-transformer metadata only to class instances. A handler that returns a plain object, such as a spread {...user} or a raw row, or one that writes through @Res(), escapes @Exclude(), so the password leaks.
solid answer
~40 s`ClassSerializerInterceptor` maps the handler's result through class-transformer's `instanceToPlain()`, and `@Exclude()` is metadata on the `UserEntity` class. A plain object carries none of it: `{ ...user, lastSeen }`, `Object.assign({}, user)` or a raw query row go out with every field. A handler that injects `@Res()` and calls `res.json(user)` never hands a value to the interceptor at all. Fixes: return instances; or put `@SerializeOptions({ type: UserEntity })` on the handler or controller so the interceptor converts plain objects with `plainToInstance()` first; or use `@Res({ passthrough: true })` and return the value. Check also that a handler-level `@SerializeOptions()` did not drop the controller's `type`: the interceptor reads them with `getAllAndOverride`, so the handler's object replaces the controller's. Then pin it with an e2e test that asserts the field is absent.
code
typescript · 22 linesimport { Controller, Get, Param, ParseIntPipe, SerializeOptions } from '@nestjs/common';
import { UserEntity } from './user.entity.js';
import { UsersService } from './users.service.js';
@Controller('users')
export class UsersController {
constructor(private readonly users: UsersService) {}
// Leaks: the spread turns the UserEntity instance into a plain object.
@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
const user = await this.users.findOne(id);
return { ...user, lastSeen: new Date() };
}
// Safe: the interceptor converts the plain row to UserEntity first.
@Get(':id/summary')
@SerializeOptions({ type: UserEntity })
async summary(@Param('id', ParseIntPipe) id: number) {
return this.users.findRow(id);
}
}go deeper
Recall that ClassSerializerInterceptor runs class-transformer over the handler's result and that @Exclude() only works on instances of the decorated class.
Explain the interceptor's steps: options from @SerializeOptions(), map() over handle(), the type option converting plain objects first, and why @Res() escapes it.
Diagnose a leak from the handler's return value: a spread, a raw row, a @Res() write or a handler-level @SerializeOptions() that dropped type. Then add a test that asserts the absence.
Weigh a denylist of @Exclude() fields against an excludeAll allowlist, and decide where in the codebase rows become instances so one rule covers every route.
## How ClassSerializerInterceptor works `ClassSerializerInterceptor` is a built-in interceptor exported from `@nestjs/common`. It relies on the **class-transformer** package, whose decorators (`@Exclude()`, `@Expose()`, `@Transform()`) attach metadata to a class. On every call the interceptor: 1. Reads `@SerializeOptions()` metadata with `reflector.getAllAndOverride()` over the handler and then the controller, and spreads it over the options passed to its constructor. 2. Calls `next.handle()` and pipes the result through RxJS `map()`. 3. Leaves non-objects (strings, numbers, `null`) and `StreamableFile` responses alone. 4. Treats an array element by element. 5. If the options carry a `type` and the value is not already an instance of it, converts it with `plainToInstance(type, value)` first. 6. Turns each value into a plain object with class-transformer, which applies the decorators **of the value's class**. The last step is the whole story: the decorators are read from the object's prototype chain. No class, no `@Exclude()`. ## Why one endpoint leaks The global binding is fine for the endpoints that return `UserEntity` instances. The leaking endpoint is almost always one of these: | Symptom in the handler | Why the field survives | Fix | |---|---|---| | returns `{ ...user, extra }` or `Object.assign({}, user)` | a spread copies own properties into a plain object and drops the prototype | return an instance, or add `@SerializeOptions({ type: UserEntity })` | | returns a raw row from a query builder or cache | the row was never a `UserEntity` | `@SerializeOptions({ type: UserEntity })`, or map rows to instances in the service | | injects `@Res()` and calls `res.json(user)` | the response is written directly; `map()` never sees a value | `@Res({ passthrough: true })` and return the value | | handler adds `@SerializeOptions({ groups: [...] })` | it replaces the controller's options, including `type` | repeat `type` in the handler's options | Default class-transformer behaviour adds one more trap: its `strategy` is `exposeAll`, so every property not marked `@Exclude()` is sent. A new column added to the entity next month is public unless someone remembers to exclude it. ## Binding it globally the right way - As a provider: `{ provide: APP_INTERCEPTOR, useClass: ClassSerializerInterceptor }`. The container injects the `Reflector` it needs. - On the application instance: `app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)))`. The constructor needs the `Reflector` to read `@SerializeOptions()`; its optional second argument holds default class-transformer options for every response. ## Making it hold - **Return instances from services.** If the persistence layer hands back plain rows, convert them in one place, not in every handler. - **Set `type` where plain objects are normal.** `@SerializeOptions({ type: UserEntity })` on a controller covers every handler in it, until a handler sets its own options. - **Consider an allowlist.** With `strategy: 'excludeAll'` in the options, only properties marked `@Expose()` are sent, so a new column stays private until someone exposes it. - **Test the absence.** An e2e test that requests each user-returning route and asserts `password` is missing catches a spread long before a reviewer does. - **Avoid `@Res()` for data responses.** Use it with `passthrough: true` when you only need to set a header or cookie. ## Walking through the code example In the example, both handlers sit under the same global interceptor: 1. `findOne()` gets a real `UserEntity` from the service, then returns `{ ...user, lastSeen: new Date() }`. The spread copies `id`, `email`, `password` and the rest into a new plain object. With no `type` option the interceptor serializes that plain object as it is, so `password` is in the body. 2. `summary()` returns a plain row, but the handler carries `@SerializeOptions({ type: UserEntity })`. The row is not an instance of `UserEntity`, so the interceptor converts it with `plainToInstance()` first; `@Exclude()` then applies and `password` is gone. The same distinction explains most leak reports: the interceptor never fails, it just serializes whatever class (or lack of one) it is handed. ## Diagnosing quickly Add a temporary log of `result instanceof UserEntity` in the handler. If it prints `false`, the interceptor is working as designed on an object it cannot recognise. If it prints `true` and the field still leaks, look at the route's `@SerializeOptions()` and at whether the response is written through `@Res()`.
- Why did adding @SerializeOptions({ groups: ['admin'] }) to one NestJS handler start leaking a field the controller's @SerializeOptions({ type: UserEntity }) used to hide?`ClassSerializerInterceptor` reads its options with `reflector.getAllAndOverride()` over the handler and the controller, so the handler's object wins and the controller's is ignored, not merged. The handler's options no longer carry `type`, plain rows are no longer converted to `UserEntity`, and `@Exclude()` stops applying. Repeat `type: UserEntity` in the handler's options.
- How do you bind NestJS's ClassSerializerInterceptor for the whole application?Register `{ provide: APP_INTERCEPTOR, useClass: ClassSerializerInterceptor }` in a module so the container injects its `Reflector`, or call `app.useGlobalInterceptors(new ClassSerializerInterceptor(app.get(Reflector)))`. The constructor's optional second argument sets default class-transformer options, such as `strategy: 'excludeAll'`, for every response.
- @Exclude() hides the field from any object with the same property names.
- A global ClassSerializerInterceptor also filters bodies a handler writes through @Res().
- A handler's @SerializeOptions() merges with the options set on its controller.
- Copying an entity with a spread keeps its class-transformer decorators working.
- With default options, a new entity column stays hidden until it is marked @Expose().