As a lead on a NestJS 12 codebase, would you standardise response shaping on ClassSerializerInterceptor or the new StandardSchemaSerializerInterceptor, and why?
answer
- denylist on classes versus allowlist schema
- unschema'd handlers pass unchanged
- mismatch means a 500
- where the team's types already live
basics
~20 sBoth read @SerializeOptions(). ClassSerializerInterceptor applies class-transformer decorators to class instances, a denylist by default; Nest 12's StandardSchemaSerializerInterceptor runs each response through a schema, and a mismatch is a 500. Choose by where the team's types already live.
solid answer
~50 sIt depends on where the team's types live and how strict responses must be. `ClassSerializerInterceptor` suits codebases built on class DTOs and entities: `@Exclude()` and `@Expose()` on the class, `@SerializeOptions({ type })` for plain rows, and class-transformer's default `exposeAll`, so a new column is public unless excluded. `StandardSchemaSerializerInterceptor`, added in Nest 12, runs each response through a Standard Schema-compatible schema chosen with `@SerializeOptions({ schema })`. A schema whose object type strips undeclared keys, as a Zod object does, makes the response an allowlist, and a mismatch becomes a 500 that the default filter logs instead of partial data. Its gap: a handler with no schema (none on the handler or controller, and no constructor default) passes unchanged. For a schema-first codebase I would pick the schema interceptor and add a test that every route declares a schema; for class-based ones, keep the class serializer with `strategy: 'excludeAll'`.
code
typescript · 33 linesimport {
Controller,
Get,
Param,
ParseIntPipe,
SerializeOptions,
StandardSchemaSerializerInterceptor,
UseInterceptors,
} from '@nestjs/common';
import { z } from 'zod';
import { UsersService } from './users.service.js';
const userResponse = z.object({
id: z.number(),
email: z.string(),
});
@Controller('users')
@UseInterceptors(StandardSchemaSerializerInterceptor)
@SerializeOptions({ schema: userResponse })
export class UsersController {
constructor(private readonly users: UsersService) {}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.users.findOne(id); // passwordHash is stripped by the schema
}
@Get()
findAll() {
return this.users.findAll(); // the item schema is applied to each element
}
}go deeper
Recall the two built-in serializers in Nest 12: one driven by class-transformer decorators, one driven by a schema, both configured through @SerializeOptions().
Explain the mechanics that differ: denylist versus allowlist, plain objects needing type, arrays handled per element, and a schema mismatch becoming a 500.
Know the gaps in production: routes with no schema pass unchanged, new columns are exposed by default on the class path, and strict schemas turn data drift into 500s.
Own the choice for the codebase: match the serializer to where types already live, plan a controller-by-controller migration, and enforce schema coverage with a test rather than review.
## The two built-in serializers NestJS 12 ships two interceptors in `@nestjs/common` that shape what a handler returns before it is sent. Both are bound like any interceptor (`@UseInterceptors()`, `app.useGlobalInterceptors()` with `app.get(Reflector)`, or `APP_INTERCEPTOR`), and both read per-route options from `@SerializeOptions()` with `getAllAndOverride`, so a handler's options replace the controller's. | | `ClassSerializerInterceptor` | `StandardSchemaSerializerInterceptor` | |---|---|---| | Since | long-standing | Nest 12 | | Rules live in | class-transformer decorators on the class | a Standard Schema-compatible schema | | Selected by | the value's class, or `@SerializeOptions({ type })` | `@SerializeOptions({ schema })` or a constructor default | | Default stance | `exposeAll`: everything not excluded is sent | what the schema's output contains | | On a bad value | serializes what it finds | throws, client gets a 500 | | Without rules | plain objects pass with every field | the response passes unchanged | | Arrays | each element | each element, so pass the item schema | Neither touches `StreamableFile` responses. Both work the same way for WebSocket and microservice handlers. ## What each guarantees, and where each leaks - **Class serializer.** Correct for instances of decorated classes. It leaks when a handler returns a plain object (a spread, a raw row) without `type`, and a new entity column is exposed by default. Switching to `strategy: 'excludeAll'` with `@Expose()` turns it into an allowlist, at the price of annotating every exposed field. - **Schema serializer.** The schema is the contract: with an object schema that strips undeclared keys, as a Zod `z.object()` does, a `passwordHash` the service returns never leaves. A record that does not match (a missing or mistyped property) is treated as a server bug: the interceptor throws an error listing the issues, the default exception filter logs it, and the client receives `500 Internal server error` rather than partial data. Its gap is coverage: a handler that has no schema anywhere is sent unchanged, even when the interceptor is bound globally. ## Costs the team carries - **Two type systems or one.** Class DTOs plus `ValidationPipe` on the way in pair naturally with the class serializer. A team that already validates requests with schemas through Nest 12's `StandardSchemaValidationPipe` can describe responses with the same library. - **Runtime work.** The schema interceptor validates every response object; a large array is validated element by element. - **Failure mode.** A strict schema turns a data drift into 500s in production. That is the point, but it needs contract tests so the drift is caught before deploy. - **Migration effort.** Both interceptors can live in one codebase, so a migration can proceed one controller at a time. ## Deciding 1. **Where do types already live?** If entities and DTOs are decorated classes, the class serializer costs nothing new. If the codebase is schema-first, the schema serializer reuses what exists. 2. **Is a silent leak or a loud failure worse?** Regulated or sensitive data favours the allowlist and its 500. 3. **Can you enforce coverage?** The schema serializer's guarantee holds only on routes that name a schema; plan a test or review rule that checks every route does. 4. **Who maintains it?** One mechanism per codebase keeps reviews simple; mixing them per controller is a migration state, not a destination. ## Configuring the schema serializer A few options decide how much of the codebase one binding covers: - A schema on the controller with `@SerializeOptions({ schema })` applies to all of its handlers; a schema on a handler takes precedence for that handler. - The constructor accepts default options: a `schema` used when neither the handler nor the controller sets one, and `validateOptions` forwarded to the schema's `~standard.validate()` call for libraries that support options. - Bound globally with `app.useGlobalInterceptors(new StandardSchemaSerializerInterceptor(app.get(Reflector)))`, or through `APP_INTERCEPTOR` so Nest injects the `Reflector`, it still leaves handlers without a schema untouched. ## A migration path 1. Bind `StandardSchemaSerializerInterceptor` on one controller and give each handler, or the controller, a schema. 2. Add an e2e assertion per route that sensitive fields are absent and the body matches the schema. 3. Move controllers over one by one, removing `@Exclude()` annotations only once no route serializes that class through the old interceptor. 4. When every controller has moved, bind the schema interceptor globally through `APP_INTERCEPTOR` and keep the coverage test. The documentation's own guidance is even-handed: `ClassSerializerInterceptor` remains supported in v12 for class-based projects, and the schema serializer is for teams whose response shape should come from a schema.
- In NestJS 12, what does a client receive when a returned object fails StandardSchemaSerializerInterceptor's schema?The interceptor throws an error that lists the schema's issues. The default exception filter logs it and the client receives a `500 Internal server error` body instead of partially serialized data. The documentation treats such a mismatch as a server bug, which is why contract tests on response shapes matter once this interceptor is in place.
- Does binding StandardSchemaSerializerInterceptor globally in NestJS 12 guarantee that no handler leaks a field?No. A handler with no schema on itself or its controller, and no default `schema` passed to the interceptor's constructor, gets its response sent unchanged. `null`, `undefined`, primitives and `StreamableFile` responses also pass through. The guarantee holds per route, so pair the global binding with a test that every data-returning route declares a schema.
- A global StandardSchemaSerializerInterceptor strips fields even where no schema is set anywhere.
- StandardSchemaSerializerInterceptor accepts only Zod schemas.
- A response that fails its serializer schema is sent with the failing fields removed.
- NestJS 12 removed ClassSerializerInterceptor in favour of schema-based serialization.
- An array response needs an array schema in @SerializeOptions().
Assumes NestJS 12: the 11-to-12 migration guide introduces StandardSchemaSerializerInterceptor, so a Nest 11 app has ClassSerializerInterceptor but not the schema interceptor.