Pipes

Pipes transform or validate input data just before it reaches the route handler.

Syntax@Param('id', ParseIntPipe) id: number

A pipe operates on the arguments passed to a route handler. It runs just before the handler and does one of two jobs:

  • Transformation - convert input, e.g. a string '42' to the number 42.
  • Validation - check input and throw an error if it is invalid.

Built-in pipes

Nest ships useful pipes like ParseIntPipe, ParseBoolPipe, and ValidationPipe. Apply a pipe to a single parameter, a handler, or globally.

Example

Example Β· typescript
import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    // id is now a real number, or a 400 was thrown
    return { id };
  }
}

When to use it

  • A developer applies ValidationPipe globally so DTO class-validator rules automatically reject malformed request bodies before any handler executes.
  • A team uses ParseIntPipe on a route parameter to ensure the :id segment is always a valid integer and throw a 400 if not.
  • An engineer writes a custom ParseEnumPipe to validate that a query parameter matches a known status enum value.

More examples

ParseIntPipe on route param

Applies ParseIntPipe inline on a parameter so NestJS returns 400 Bad Request automatically if the segment is not a valid integer.

Example Β· ts
import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return { id };   // id is guaranteed to be a number
  }
}

Global ValidationPipe in bootstrap

Registers the ValidationPipe globally with whitelist and transform options, automatically validating and coercing every incoming DTO.

Example Β· ts
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,      // strip unknown fields
      forbidNonWhitelisted: true,  // throw on unknown fields
      transform: true,     // coerce types automatically
    }),
  );
  await app.listen(3000);
}
bootstrap();

Custom pipe implementation

Implements PipeTransform to create a custom pipe that parses and validates a value must be a positive integer.

Example Β· ts
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class PositiveIntPipe implements PipeTransform<string, number> {
  transform(value: string): number {
    const val = parseInt(value, 10);
    if (isNaN(val) || val <= 0) {
      throw new BadRequestException('Value must be a positive integer');
    }
    return val;
  }
}

Discussion

  • Be the first to comment on this lesson.