In NestJS, what is a pipe, what does its transform() method receive, and what happens when it throws?
answer
- two jobs at the boundary
- one interface, one method
- a value and its metadata
- what the return value replaces
- what an exception does to the call
basics
~20 sA 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 sA 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
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.
Explain what ArgumentMetadata carries and why metatype reads Object for an interface, then show binding at parameter, method or controller, and global scope.
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.
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