Concept Flow - Custom pipes
Request received
Pipe invoked
Transform or Validate input
Valid
Pass to
Controller
When a request comes in, NestJS runs the custom pipe to check or change data before the controller uses it.
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'; @Injectable() export class ParseIntPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { const val = parseInt(value, 10); if (isNaN(val)) { throw new BadRequestException('Validation failed'); } return val; } }
| Step | Input Value | Action | Result | Next Step |
|---|---|---|---|---|
| 1 | "123" | parseInt("123") | 123 (number) | Pass to controller |
| 2 | "abc" | parseInt("abc") | NaN | Throw BadRequestException |
| 3 | null | parseInt(null) | 0 | Pass to controller |
| 4 | "42abc" | parseInt("42abc") | 42 (number) | Pass to controller |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| value | undefined | "123" | "abc" | null | "42abc" |
| val | undefined | 123 | NaN | 0 | 42 |
Custom pipes in NestJS transform or validate data before it reaches controllers. They implement PipeTransform with a transform() method. If validation fails, throw an exception to stop the request. Return the transformed value to pass it on. Useful for type conversion and input checks.