Built-in Pipes

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

NestJS comes with nine built-in pipes available out-of-the-box.

Overview

To save you from writing standard transformation and validation logic, Nest provides a suite of ready-to-use pipes exported from the @nestjs/common package.

These pipes handle the most common data types sent via HTTP URLs (which are inherently strings).

Key Concepts

Here is the list of the built-in pipes:

  1. ValidationPipe
  2. ParseIntPipe
  3. ParseFloatPipe
  4. ParseBoolPipe
  5. ParseArrayPipe
  6. ParseUUIDPipe
  7. ParseEnumPipe
  8. DefaultValuePipe
  9. ParseFilePipe

Code Examples

Parsing Numbers

URL parameters are strings. Use these to safely convert them to numbers.

// GET /products/42
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) { ... }

// GET /products?price=9.99
@Get()
findCheap(@Query('price', ParseFloatPipe) price: number) { ... }

Parsing Enums

Extremely useful for ensuring a query parameter matches a specific set of allowed strings.

enum SortOrder {
  ASC = 'asc',
  DESC = 'desc',
}

@Get()
findAll(@Query('sort', new ParseEnumPipe(SortOrder)) sort: SortOrder) {
  // If the user sends ?sort=xyz, Nest automatically throws a 400 Bad Request
}

Parsing Arrays (from comma-separated strings)

If a user sends ?ids=1,2,3, ParseArrayPipe can automatically split and convert the types.

@Get()
findByIds(
  @Query('ids', new ParseArrayPipe({ items: Number, separator: ',' }))
  ids: number[],
) {
  // ids is now [1, 2, 3]!
}

Using DefaultValuePipe

Often used in combination with other parsing pipes to provide a fallback when the user omits a query parameter.

@Get()
findAll(
  @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
) {
  // If ?page is missing, page = 1.
  // If ?page=5, page = 5.
  // If ?page=abc, ParseIntPipe throws a 400 Bad Request.
}

Best Practices

  • Customize Error Messages: If you want to change the default “Validation failed (numeric string is expected)” error message from ParseIntPipe, pass a custom exception factory: new ParseIntPipe({ exceptionFactory: () => new BadRequestException('ID must be a number') }).
  • Chain Pipes Thoughtfully: When chaining DefaultValuePipe with a parsing pipe, order matters! Nest executes pipes from left to right. DefaultValuePipe should always be the first in the chain, so it can inject the default string before the parsing pipe tries to parse it.