skip to content

Pipes and Validation

Pipes transform and validate handler arguments: ValidationPipe over class-validator DTOs, or v12's StandardSchemaValidationPipe over a schema on @Body(). Interviewers ask how bad input becomes a 400.

on this pageshow

explore

questions

6

In NestJS, what is a pipe, what does its transform() method receive, and what happens when it throws?

level: juniorimportance: must knowfreq 70%

answer

  1. two jobs at the boundary
  2. one interface, one method
  3. a value and its metadata
  4. what the return value replaces
  5. what an exception does to the call

basics

~20 s

A NestJS pipe is an @Injectable class implementing PipeTransform. Its transform(value, metadata) gets one handler argument before the handler runs; what it returns replaces that argument, and if it throws, the handler is skipped and the exception becomes the response.

solid answer

~50 s

A pipe is a class marked `@Injectable()` that implements `PipeTransform`, so it has one method, `transform(value, metadata)`. Nest calls it for a handler argument immediately before the handler is invoked: `value` is the extracted argument (a route param, a query value, the body) and `metadata` is an `ArgumentMetadata` whose `type` says where it came from (`'body'`, `'query'`, `'param'` or `'custom'`), whose `metatype` is the declared parameter type and whose `data` is the string passed to the decorator. Whatever `transform` returns, synchronously or as a promise, replaces the argument; that is how `ParseIntPipe` hands the handler `42` instead of `'42'`, while a validating pipe returns the value unchanged. If `transform` throws, the handler never runs: pipes sit inside the exceptions zone, so a `BadRequestException` becomes a 400. Pipes bind per parameter, per method or controller with `@UsePipes()`, or globally.

go deeper

for a junior

Recall the contract: a class implementing PipeTransform with one transform(value, metadata) method, the return value replacing the argument, and a thrown exception stopping the handler.

for a middle

Explain what ArgumentMetadata carries and why metatype reads Object for an interface, then show binding at parameter, method or controller, and global scope.

for a senior

Show that you keep boundary checks in pipes, configure built-ins through instances, and know why a useGlobalPipes pipe has no injection while an APP_PIPE provider does.

for a principal

Talk about which pipes a team registers globally so no endpoint ships unguarded, and where input-shape checks end and domain rules in services begin.

## What a pipe is A **pipe** in NestJS is a class decorated with `@Injectable()` that implements the `PipeTransform` interface from `@nestjs/common`. Nest places it between the incoming request and a controller's **route handler**: the pipe receives an argument destined for the handler, may change it or reject it, and only then does Nest call the handler. The documentation names two use cases: - **Transformation**: convert input into the form the handler wants, such as a numeric string into a number. - **Validation**: check the input and pass it through unchanged when it is valid, or throw an exception when it is not. Nest ships built-in pipes for both. `ParseIntPipe`, `ParseFloatPipe`, `ParseBoolPipe`, `ParseArrayPipe`, `ParseUUIDPipe`, `ParseEnumPipe`, `ParseDatePipe`, `ParseFilePipe` and `DefaultValuePipe` work on single values, while `ValidationPipe` and `StandardSchemaValidationPipe` validate whole objects. ## The transform() contract `PipeTransform<T, R>` is generic: `T` is the type of the incoming value and `R` the return type of its single method, `transform(value, metadata)`. - `value` is the argument currently being processed, already extracted from the request by its parameter decorator (`@Param('id')`, `@Query('page')`, `@Body()`). - `metadata` is an `ArgumentMetadata` object describing that argument. - The return value **replaces** the argument. When several pipes apply, each receives the previous one's output, and the handler gets what the last one returned. - `transform` may be `async`; Nest awaits a returned promise before moving on, which is why validators that do asynchronous checks fit here. | `ArgumentMetadata` field | What it holds | |---|---| | `type` | `'body'`, `'query'`, `'param'` or `'custom'` (a custom parameter decorator) | | `metatype` | The declared parameter type, such as `Number` or a DTO class; `undefined` without a type annotation | | `data` | The string passed to the decorator, as in `@Body('email')`; `undefined` for a bare `@Body()` | One trap hides in `metatype`: TypeScript interfaces disappear when the code is compiled, so a parameter typed with an interface reports `Object`. A pipe that relies on `metatype` cannot see the interface at all. ## When transform throws Pipes run inside Nest's **exceptions zone**. If `transform` throws: 1. The route handler is not executed. 2. The exception is handled by the exceptions layer: the global exception filter plus any exception filters applied to the current context. 3. An `HttpException` subclass keeps its own status. `BadRequestException` produces a 400 with a body such as `{"statusCode":400,"message":"Validation failed (numeric string is expected)","error":"Bad Request"}`, which is exactly what `ParseIntPipe` returns for `/orders/abc`. This is why the documentation recommends pipes as the place to validate data entering the application from outside: bad input is stopped at the system boundary, before business code sees it. ## Binding a pipe A pipe does nothing until it is bound to a context: - **Parameter scope**: pass it to the parameter decorator, as in `@Param('id', ParseIntPipe) id: number`. Only that argument goes through it. - **Method or controller scope**: `@UsePipes(...)` on a handler or on a controller class applies the pipe to the arguments of those handlers. - **Global scope**: `app.useGlobalPipes(new ValidationPipe())` in the bootstrap code, or a provider `{ provide: APP_PIPE, useClass: ValidationPipe }` declared in a module. You can pass a **class** (`ParseIntPipe`) and let Nest instantiate it, which enables dependency injection, or an **instance** (`new ParseIntPipe({ errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE })`) when the pipe needs options. A pipe handed to `useGlobalPipes()` is built outside any module, so it cannot have dependencies injected; registering it through `APP_PIPE` lets the container construct it, and it is still global whichever module declares it. ## A minimal custom pipe Every pipe has the same shape: take a value, return a value or throw. ```typescript import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'; @Injectable() export class PositiveIntPipe implements PipeTransform<string, number> { transform(value: string, metadata: ArgumentMetadata): number { const n = Number(value); if (!Number.isInteger(n) || n <= 0) { throw new BadRequestException(`${metadata.data} must be a positive integer`); } return n; } } ``` Bound as `@Param('id', PositiveIntPipe) id: number`, it gives the handler a real positive number, or answers 400 before the handler runs. A missing or empty value converts to `NaN` or `0` and is rejected by the same check.

  • Why pass ParseIntPipe as a class in one place and as new ParseIntPipe({...}) in another?
    Passing the class leaves instantiation to Nest, which enables dependency injection and suits a pipe whose defaults are fine. Passing an instance is how you configure a built-in pipe, for example `new ParseIntPipe({ errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE })` to answer 406 instead of 400, or `{ optional: true }` to let a missing value through.
  • Why can't a pipe registered with app.useGlobalPipes() inject a service, and what fixes it?
    `useGlobalPipes()` receives an instance you constructed yourself in the bootstrap code, outside any module, so Nest never resolves its constructor parameters. Register it instead as a provider, `{ provide: APP_PIPE, useClass: MyPipe }`, in a module: the container builds it with its dependencies, and it still applies to every route, whichever module declares it.

  • Pipes run after the handler to reshape what it returns
  • A validation pipe returns true or false instead of the value
  • If a pipe throws, Nest still calls the handler with the original value
  • An interface-typed parameter gives the pipe its real type in metatype
  • A pipe given to useGlobalPipes can inject providers through its constructor
open as a page

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

level: middleimportance: must knowfreq 70%

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.

open as a page

In NestJS, how do ParseIntPipe and DefaultValuePipe handle a page query parameter that is missing, empty or non-numeric?

level: middleimportance: should knowfreq 45%

basics

~20 s

ParseIntPipe accepts only integer strings or integer numbers and throws a 400 for anything else, including a missing value unless optional: true. DefaultValuePipe, listed before it, swaps null or undefined for a default, but an empty string is not missing.

open as a page

In NestJS 12, how does StandardSchemaValidationPipe validate @Body({ schema }), and what happens if the pipe is never registered?

level: middleimportance: should knowfreq 35%

basics

~20 s

In NestJS 12, @Body({ schema }) only attaches the schema as metadata. StandardSchemaValidationPipe reads it, calls the schema's ~standard.validate, throws a 400 listing path-prefixed issues, and passes the schema's output on. Without the pipe registered, nothing validates.

open as a page

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%

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 }).

open as a page

As lead of a NestJS 12 codebase built on class-validator DTOs, how would you decide whether to adopt StandardSchemaValidationPipe, and how would you migrate?

level: principalimportance: should knowfreq 25%

basics

~20 s

Nest 12 keeps ValidationPipe fully supported, so adopting StandardSchemaValidationPipe is a choice, not an upgrade task. Weigh schema-inferred types, coercion and arrays against DTO classes' mapped types and Swagger plugin, then register both pipes and migrate endpoint by endpoint.

open as a page