ParseBoolPipe
⭐ Interview Importance: LOW
⏱️ Revision Time: 12 min
The ParseBoolPipe ensures that a parameter can be evaluated as a boolean, and transforms the incoming string into a true JavaScript boolean type.
Overview
In HTTP GET requests, query parameters are always transmitted as strings. If a client sends /users?active=true, your NestJS controller will receive the string "true".
This can lead to dangerous bugs because in JavaScript, the string "false" is truthy (if ("false") evaluates to true!). ParseBoolPipe solves this by strictly parsing the string into a real boolean.
Key Concepts
- Strict Parsing: It only accepts specific string values. If the value cannot be parsed, it throws a 400 Bad Request exception.
- Accepted Values: By default, it accepts
"true","false",true, andfalse. - Not for Numbers: Unlike some loose JavaScript comparisons, passing
"1"or"0"toParseBoolPipewill result in a validation error.
Code Examples
Basic Usage
import { Controller, Get, Query, ParseBoolPipe } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get()
findAll(
// The string "true" from the URL becomes the boolean true
@Query('active', ParseBoolPipe) active: boolean
) {
// We can safely use strict equality or truthiness checks now
if (active === true) {
return 'Finding active users...';
} else {
return 'Finding ALL users...';
}
}
}
Customizing the Error Message
If the client sends ?active=yes, the pipe will throw an error. You can customize the status code or message.
import { HttpStatus } from '@nestjs/common';
@Get()
findAll(
@Query('active', new ParseBoolPipe({
errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE,
// Note: You can also provide a custom exceptionFactory function for full control
}))
active: boolean
) {
// ...
}
Best Practices
- Combine with DefaultValuePipe: Boolean flags are usually optional. To prevent the pipe from crashing when the client omits the parameter entirely, always chain it with
DefaultValuePipe. (e.g.,@Query('active', new DefaultValuePipe(false), ParseBoolPipe)). - Never Trust Query Booleans: Never use
@Query('flag') flag: booleanwithout a pipe. TypeScript will type it as a boolean at compile time, but at runtime, it will be a string. Always useParseBoolPipefor query booleans to prevent truthiness bugs.