0
0
NestJSframework~5 mins

Built-in pipes (ParseIntPipe, ParseBoolPipe) in NestJS

Choose your learning style9 modes available
Introduction

Pipes help convert and validate data in NestJS. ParseIntPipe and ParseBoolPipe make sure your data is the right type, like numbers or true/false.

When you get a number as a string from a URL and want to use it as a number in your code.
When you receive a true/false value as a string and want to use it as a boolean.
When you want to avoid manual checks and conversions for common data types in your route handlers.
Syntax
NestJS
import { ParseIntPipe, ParseBoolPipe } from '@nestjs/common';

@Get(':id')
getById(@Param('id', ParseIntPipe) id: number) {
  // id is a number here
}

@Get('active/:status')
getByStatus(@Param('status', ParseBoolPipe) status: boolean) {
  // status is a boolean here
}

Use pipes inside parameter decorators like @Param(), @Query(), or @Body() to transform input data.

If the input cannot be converted, NestJS will automatically return a 400 error.

Examples
This converts the 'id' parameter from string to number automatically.
NestJS
@Get(':id')
getUser(@Param('id', ParseIntPipe) id: number) {
  return `User ID is ${id}`;
}
This converts the 'status' parameter from string to boolean (true or false).
NestJS
@Get('active/:status')
getActive(@Param('status', ParseBoolPipe) status: boolean) {
  return `Active status is ${status}`;
}
ParseIntPipe can also be used with query parameters.
NestJS
@Get('query')
getQuery(@Query('page', ParseIntPipe) page: number) {
  return `Page number is ${page}`;
}
Sample Program

This controller has two routes. One converts the 'id' param to a number. The other converts 'status' param to a boolean. If conversion fails, NestJS sends a 400 error automatically.

NestJS
import { Controller, Get, Param, ParseIntPipe, ParseBoolPipe } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get(':id')
  getItemById(@Param('id', ParseIntPipe) id: number) {
    return `Item ID is ${id}`;
  }

  @Get('available/:status')
  getItemAvailability(@Param('status', ParseBoolPipe) status: boolean) {
    return `Item availability is ${status}`;
  }
}
OutputSuccess
Important Notes

ParseIntPipe converts strings to integers using parseInt(), which truncates decimals (e.g., '3.14' becomes 3) and rejects non-numeric inputs with an error.

ParseBoolPipe accepts 'true', 'false', '1', '0' (case insensitive) as valid boolean strings.

You can customize error messages by extending these pipes if needed.

Summary

ParseIntPipe and ParseBoolPipe automatically convert string inputs to number and boolean types.

They help keep your code clean by avoiding manual parsing and validation.

Invalid inputs cause NestJS to return a 400 error, improving API reliability.