skip to content

A NestJS app has a global ValidationPipe with transform: true, yet GET /orders/abc reaches the handler with id NaN and bulk order arrays go unvalidated. Why?

level: seniorimportance: should knowfreq 40%

answer

  1. what the pipe chooses to skip
  2. metatype decides
  3. converted is not validated
  4. arrays, interfaces, custom decorators
  5. a parse pipe per parameter

basics

~20 s

ValidationPipe validates only class-typed parameters. A number param is merely converted with unary plus, so 'abc' becomes NaN, and a CreateOrderDto[] body reports metatype Array and is skipped. Add ParseIntPipe and ParseArrayPipe({ items: CreateOrderDto }).

solid answer

~40 s

`ValidationPipe` decides by the parameter's `metatype`. It validates only classes; for `String`, `Number`, `Boolean`, `Array`, `Object`, `Buffer` and `Date` it skips validation, and with `transform: true` it merely converts a named param or query value with unary plus, so `'abc'` becomes `NaN` and the handler runs. A `CreateOrderDto[]` body reports `Array`, because TypeScript emits no element type, so nothing inside is checked. The same silent skip hits a DTO declared as an interface (it reports `Object`), a DTO pulled in with `import type`, which is erased at runtime, and custom parameter decorators unless `validateCustomDecorators` is on. Fix the id with `@Param('id', ParseIntPipe)`, which runs after the global pipe and rejects `NaN`, or with a params class; fix the array with `new ParseArrayPipe({ items: CreateOrderDto, whitelist: true })` or a wrapper class with nested validation.

go deeper

for a junior

Recall that ValidationPipe checks DTO classes and that ParseIntPipe is what rejects a non-numeric id with a 400.

for a middle

Explain how metatype drives ValidationPipe, which built-in types it skips, and why an array or interface parameter is never validated.

for a senior

Diagnose the NaN and the unvalidated array from the pipe's skip rules, explain why ParseIntPipe after the global pipe still rejects NaN, and close each gap with a test.

for a principal

Decide which guarantees the global pipe gives a team and which each endpoint must add, and make fail-open validation gaps visible in review and tests.

## How ValidationPipe decides what to validate `ValidationPipe` works from the `metatype` field of the pipe's `ArgumentMetadata`: the declared type of the handler parameter, which Nest reads from the type metadata TypeScript emits for decorated methods (`emitDecoratorMetadata`). Before doing anything, the pipe asks whether that type is worth validating. It is **not** when: - `metatype` is missing (no type annotation, or plain JavaScript); - `metatype` is one of `String`, `Boolean`, `Number`, `Array`, `Object`, `Buffer` or `Date`; - the argument comes from a custom parameter decorator (`type === 'custom'`) and `validateCustomDecorators` is not set. In every such case the pipe validates nothing. Without `transform` it returns the value as is; with `transform: true` it runs a light primitive conversion and returns that. No exception, no warning: the request simply reaches the handler. ## Gap 1: primitive parameters are converted, not validated For a named `@Param()` or `@Query()` value, `transform: true` converts by declared type: | Declared type | Conversion | Surprising result | |---|---|---| | `number` | unary plus | `'abc'` becomes `NaN`, `''` becomes `0` | | `boolean` | `true` only for `true` or `'true'` | `'yes'` becomes `false` | | `string` | `String(value)` | none | So `GET /orders/abc` with `@Param('id') id: number` hands the handler `NaN`, and a lookup by `NaN` quietly finds nothing. The pipe never rejects a primitive. ## Gap 2: arrays and generics TypeScript emits no metadata for generic types, so `@Body() orders: CreateOrderDto[]` reports `Array`, and the elements are never validated. The documented fixes: - **`ParseArrayPipe`** with `items`: `@Body(new ParseArrayPipe({ items: CreateOrderDto, whitelist: true }))`. It builds its **own internal `ValidationPipe`** (with `transform` on), so the global pipe's options do not reach the items; repeat `whitelist` and friends here. By default it stops at the first invalid item; `stopAtFirstError: false` collects every failure, prefixing each message with the item index such as `[1]`. - **A wrapper class** whose property holds the array, validated with class-validator's nested-validation decorators. Why nested rules need explicit wiring is a framework-neutral question about declarative constraints. ## Gap 3: types the pipe cannot see - A DTO declared as an **interface** reports `Object`, because interfaces vanish at compile time. - A DTO imported with **`import type`** is erased at runtime; the docs say to use a normal import. - A parameter from a **custom decorator** built with `createParamDecorator()` is skipped unless the pipe has `validateCustomDecorators: true`. ## Why ParseIntPipe still works after the global pipe Global pipes run before the pipes bound to a parameter, and each pipe receives the previous one's output. With `@Param('id', ParseIntPipe)`: 1. The global `ValidationPipe` converts `'abc'` to `NaN`. 2. `ParseIntPipe` accepts numbers as well as strings, but checks that the string form is an optional minus sign and digits. `'NaN'` is not, so it throws `Validation failed (numeric string is expected)` with a 400. 3. A valid `'7'` becomes `7` in step 1 and passes step 2 unchanged. ## Closing the gaps 1. Bind a parse pipe to every primitive path or query parameter that matters: `ParseIntPipe`, `ParseUUIDPipe`, `ParseBoolPipe`, `ParseEnumPipe`. 2. Or group route values into a params class (`@Param() params: FindOrderParams`) whose fields carry class-validator rules, with `@Type(() => Number)` for numeric ones. 3. Give array bodies `ParseArrayPipe` with `items` and the same `whitelist` options you use globally. 4. Declare DTOs as classes, import them normally, and set `validateCustomDecorators` where custom decorators carry input. 5. Add a test per endpoint that sends a malformed value and asserts a 400, because each gap fails open and silently. ## Spotting the gaps in review The skip rules are mechanical, so a reviewer can catch them from the handler signature alone: - a `@Param()` or `@Query()` typed `number`, `boolean` or a union of string literals with no parse pipe beside it; - a body typed as an array, a `Record` or an interface; - a DTO imported on an `import type` line; - a custom decorator that extracts user input, such as a header, with no `validateCustomDecorators` on the pipe that should check it. None of these produces a compiler error or a startup warning; the first signal is usually bad data reaching a service.

  • Why does ?active=yes arrive as false instead of a 400 with transform: true and active: boolean?
    For a named query value typed `boolean`, `ValidationPipe`'s primitive conversion returns `true` only for `true` or `'true'`; everything else except `undefined` becomes `false`, and no validation runs. Bind `ParseBoolPipe`, which accepts only `'true'`, `'false'` or real booleans and otherwise throws `Validation failed (boolean string is expected)`.
  • Why does ParseArrayPipe ignore the whitelist: true set on the global ValidationPipe?
    `ParseArrayPipe` validates each item with its own internal `ValidationPipe`, created from the options passed to `ParseArrayPipe` (plus `transform: true`). The global pipe already skipped the body because its metatype is `Array`, so its options never touch the items. Pass `whitelist` and `forbidNonWhitelisted` to `ParseArrayPipe` itself.

  • A global ValidationPipe rejects any path parameter that does not match its TypeScript type
  • transform: true makes ValidationPipe validate primitive parameters too
  • Typing a body as CreateOrderDto[] validates every element
  • A DTO declared as a TypeScript interface is validated like a class
  • ParseArrayPipe inherits whitelist and other options from the global ValidationPipe