Pipes help convert and validate data in NestJS. ParseIntPipe and ParseBoolPipe make sure your data is the right type, like numbers or true/false.
Built-in pipes (ParseIntPipe, ParseBoolPipe) in 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.
@Get(':id') getUser(@Param('id', ParseIntPipe) id: number) { return `User ID is ${id}`; }
@Get('active/:status') getActive(@Param('status', ParseBoolPipe) status: boolean) { return `Active status is ${status}`; }
@Get('query') getQuery(@Query('page', ParseIntPipe) page: number) { return `Page number is ${page}`; }
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.
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}`; } }
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.
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.