skip to content

In NestJS 12, what do ValidationPipe's whitelist, forbidNonWhitelisted and transform options do to a create-order request body?

level: middleimportance: must knowfreq 70%

answer

  1. strip, reject or convert
  2. only decorated properties survive
  3. one option needs its partner
  4. plain object versus DTO instance
  5. a body string stays a string

basics

~20 s

In NestJS 12, ValidationPipe's whitelist strips body properties with no class-validator decorator, forbidNonWhitelisted (alongside it) rejects them with a 400, and transform hands the handler a real DTO instance but does not coerce body fields by itself.

solid answer

~50 s

With no options, `ValidationPipe` runs the DTO's class-validator decorators and, on success, passes the original plain body through, extra properties included. `whitelist: true` strips every property that carries no validation decorator, so an `isAdmin` or `price` smuggled into a create-order body disappears (`@Allow()` keeps a field that has no other rule). `forbidNonWhitelisted: true` turns that stripping into a 400 with messages like `property isAdmin should not exist`, and it does nothing unless `whitelist` is also on. `transform: true` makes the handler receive a `CreateOrderDto` instance instead of a plain object and converts named `@Param()` and `@Query()` primitives by their declared type; a body field sent as `"42"` still fails `@IsInt()` unless you add `@Type(() => Number)` or `transformOptions: { enableImplicitConversion: true }`. Failures are 400 by default; `errorHttpStatusCode`, `exceptionFactory` and Nest 12's `errorFormat: 'grouped'` reshape them.

code

plaintext · 8 lines
plaintext
POST /orders
Content-Type: application/json

{"productId": 1, "quantity": 2, "isAdmin": true}

HTTP/1.1 400 Bad Request

{"message":["property isAdmin should not exist"],"error":"Bad Request","statusCode":400}

go deeper

for a junior

Recall that ValidationPipe checks class-validator decorators on a DTO, that whitelist strips unknown fields, and that failures become a 400 with a message array.

for a middle

Explain why forbidNonWhitelisted needs whitelist, what transform does and does not convert, and when the handler gets a plain object instead of a DTO instance.

for a senior

Show you would set whitelist with forbidNonWhitelisted and transform globally, add @Type for numeric body fields, and check filters before switching errorFormat to grouped.

for a principal

Frame the strip-versus-reject policy as a client-contract decision, and own how validation messages stay stable when options or formats change across services.

## The setup: a DTO and a global pipe `ValidationPipe` is the built-in pipe in `@nestjs/common` that validates **DTO classes** (data transfer objects) annotated with decorators from the class-validator library, with class-transformer turning plain JSON into class instances; both libraries must be installed. A create-order endpoint might look like this: ```typescript import { IsInt, Min } from 'class-validator'; export class CreateOrderDto { @IsInt() productId: number; @IsInt() @Min(1) quantity: number; } // main.ts app.useGlobalPipes( new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }), ); ``` For a parameter whose declared type is a class, the pipe converts the plain body into an instance with class-transformer's `plainToInstance`, runs class-validator's `validate` on it and throws if any constraint fails. ## What each option changes | Option | Default | Effect on the create-order body | |---|---|---| | `whitelist` | off | Removes every property with no validation decorator, such as `isAdmin` | | `forbidNonWhitelisted` | off | With `whitelist`, rejects such a property: 400 `property isAdmin should not exist`; without `whitelist`, no effect | | `transform` | off | The handler receives a `CreateOrderDto` instance; named param and query primitives are converted by declared type | | `errorHttpStatusCode` | 400 | Status of the thrown exception, for example 422 | | `errorFormat` | `'list'` | `'grouped'` makes `message` an object keyed by property path (new in Nest 12) | | `disableErrorMessages` | off | The response keeps the status but drops the detailed messages | What the handler actually receives depends on the combination: - **No options**: the original body, unknown properties included, once validation passes. - **`whitelist` without `transform`**: a **plain object** with the undecorated properties removed. Nest validates an instance and, because non-default validator options are set, converts it back with `classToPlain`; `instanceof CreateOrderDto` is false. - **`transform`**: a real `CreateOrderDto` instance, so class methods and getters work. Note that `whitelist` keys off decorators, not declarations: a property declared on the class but carrying no class-validator decorator is stripped too, which is what `@Allow()` exists for. ## What transform does not do `transform: true` changes the object's class; it does not reinterpret field values. `plainToInstance` copies JSON values as they are, so `{ "productId": "42" }` keeps a string and fails `@IsInt()` with `productId must be an integer number`. To accept numeric strings in a body: 1. Add `@Type(() => Number)` from class-transformer to that property, converting just that field. 2. Or set `transformOptions: { enableImplicitConversion: true }`, which converts properties to their emitted design types (this relies on `emitDecoratorMetadata`, which Nest projects enable). 3. Or keep the contract strict and require clients to send numbers. For a named path or query parameter such as `@Param('id') id: number`, `transform` does convert, but with plain unary plus and no validation, which is a separate trap. ## Defaults Nest sets for you - Unless you pass it, Nest sets class-validator's `forbidUnknownValues` to `false`, while class-validator's own README makes it `true` by default and advises keeping it. - A failure throws `BadRequestException`, and the default `'list'` format puts every violated constraint message into a `message` array. - `exceptionFactory` receives class-validator's `ValidationError[]` and returns any exception you like, for teams with a house error contract. - `disableErrorMessages: true` keeps the status but returns only `{"message":"Bad Request","statusCode":400}`, for services that prefer not to echo rule details back to callers. - `errorHttpStatusCode: 422` makes the default factory throw `UnprocessableEntityException` instead, with the same message array; whether 400 or 422 is the right answer is an API-design question rather than a Nest one. ## Where to bind it Most teams bind `ValidationPipe` once, globally, so every class-typed body, query object or params object is checked with the same options. Binding a second instance on one parameter, as in `@Body(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))` on a sensitive route, adds to the global one rather than replacing it: both run, the global one first. A per-route instance can therefore make a route stricter, never looser, because a request the global pipe rejects never reaches it. ## Error formats in Nest 12 Nest 12 added `errorFormat`. With `'list'`, a body failing two rules returns `"message": ["productId must be an integer number", "quantity must not be less than 1"]`. With `'grouped'`, the same failure returns `"message": {"productId": ["productId must be an integer number"], "quantity": ["quantity must not be less than 1"]}`. The source warns that `message` then changes from `string[]` to `Record<string, string[]>`, so any exception filter or interceptor that assumes an array must be updated before switching.

  • Why does a body field sent as "42" still fail @IsInt() with transform: true?
    `transform` only makes the pipe hand over the instance `plainToInstance` built, and that conversion copies JSON values as they are. class-transformer converts a property only when told to: `@Type(() => Number)` on the field, or `transformOptions: { enableImplicitConversion: true }`, which uses the emitted design type of each property.
  • With whitelist: true but transform off, what does the handler receive?
    A plain object with the undecorated properties removed, not a `CreateOrderDto` instance. Nest validates an instance, which is where class-validator strips the extra fields, then converts it back to a plain object with `classToPlain` because non-default validator options are set. Code that relies on `instanceof` or DTO methods needs `transform: true`.
  • Why might a team choose forbidNonWhitelisted over whitelist alone?
    Silent stripping hides client mistakes: a misspelled field is accepted and quietly ignored. Rejecting with `property x should not exist` surfaces the bug at once. The cost is stricter coupling, since clients that send extra fields, for example after a field was removed, start getting 400s.

  • forbidNonWhitelisted rejects extra fields even without whitelist
  • whitelist removes the properties that fail validation
  • transform: true turns a "42" body field into a number for @IsInt()
  • Without transform the handler still receives a CreateOrderDto instance
  • whitelist keeps any property declared on the class, decorated or not

Assumes NestJS 12, where ValidationPipe gained the errorFormat option ('list' by default, or 'grouped'); the migration guide lists no change to whitelist, forbidNonWhitelisted or transform.