skip to content

In NestJS, how do ParseIntPipe and DefaultValuePipe handle a page query parameter that is missing, empty or non-numeric?

level: middleimportance: should knowfreq 45%

answer

  1. missing is not optional
  2. the optional flag
  3. default first, then parse
  4. integer strings only
  5. an empty string is not nil

basics

~20 s

ParseIntPipe accepts only integer strings or integer numbers and throws a 400 for anything else, including a missing value unless optional: true. DefaultValuePipe, listed before it, swaps null or undefined for a default, but an empty string is not missing.

solid answer

~40 s

`ParseIntPipe` checks that the value is a string or number made of an optional minus sign and digits, then returns `parseInt(value, 10)`. Anything else, such as `'abc'`, `'4.2'`, `'1e3'`, `''` or a missing value, makes it throw `BadRequestException` with `Validation failed (numeric string is expected)`, unless it was constructed with `optional: true`, which lets `null` or `undefined` straight through. To default a missing `?page`, put `new DefaultValuePipe(1)` before the parser: `@Query('page', new DefaultValuePipe(1), ParseIntPipe)`. Pipes on one parameter run in the order listed, and `DefaultValuePipe` only replaces `null`, `undefined` or a `NaN` number, so `?page=` (an empty string) still reaches `ParseIntPipe` and fails. Every `Parse*` pipe also takes `errorHttpStatusCode` or an `exceptionFactory` when 400 is not the answer you want.

code

typescript · 17 lines
typescript
import { Controller, Get, Query, DefaultValuePipe, ParseIntPipe, ParseEnumPipe } from '@nestjs/common';

export enum OrderStatus {
  Pending = 'pending',
  Paid = 'paid',
}

@Controller('orders')
export class OrdersController {
  @Get()
  findAll(
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
    @Query('status', new ParseEnumPipe(OrderStatus, { optional: true })) status?: OrderStatus,
  ) {
    return { page, status };
  }
}

go deeper

for a junior

Recall that ParseIntPipe turns an integer string into a number or answers 400, and that DefaultValuePipe goes before it to supply a default.

for a middle

Explain the integer-string check, the optional flag versus DefaultValuePipe, left-to-right order on one parameter, and why an empty string is not treated as missing.

for a senior

Show you can predict what a global ValidationPipe with transform does to a value before parameter pipes see it, and reshape errors with errorHttpStatusCode or exceptionFactory.

for a principal

Weigh whether a team defaults to optional parameters or explicit defaults, and how consistently parse errors should look across services that clients integrate with.

## What ParseIntPipe accepts `ParseIntPipe` from `@nestjs/common` is a **transformation pipe**: it turns a route or query value, which always arrives as a string, into a JavaScript integer, or rejects the request. Its check is stricter than JavaScript's own `parseInt`: - the value must be a `string` or a `number`; - its string form must be an optional minus sign followed by digits only; - it must be finite. Only then does the pipe return `parseInt(String(value), 10)`. Anything else throws, by default, a `BadRequestException` whose message is `Validation failed (numeric string is expected)`. | Input for `?page=` | Result with `ParseIntPipe` | |---|---| | `'42'` | the number `42` | | `'-7'` | the number `-7` | | `'4.2'` | 400, not truncated to `4` | | `'1e3'` | 400, exponent notation rejected | | `''` (an empty value) | 400 | | parameter absent (`undefined`) | 400 | | absent, with `new ParseIntPipe({ optional: true })` | `undefined` passed to the handler | ## Missing values: optional versus DefaultValuePipe By default the `Parse*` pipes expect the value to be defined and throws on `null` or `undefined`. Two tools change that: 1. **`optional: true`** on the parse pipe passes `null` or `undefined` through untouched. The handler must cope with an absent value. 2. **`DefaultValuePipe`** supplies a value. `new DefaultValuePipe(1)` returns `1` whenever its input is `null`, `undefined` or a `NaN` number, and otherwise returns the input unchanged. Pick `optional` when "not given" means something different from any concrete value (no filter at all); pick `DefaultValuePipe` when the endpoint has a sensible default (page 1). ## Order on a single parameter Pipes listed in one parameter decorator run **left to right**, each receiving the previous one's output: ```typescript @Get() findAll(@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number) { return this.ordersService.findPage(page); } ``` Here a missing `page` becomes `1`, which `ParseIntPipe` accepts because it takes numbers as well as strings. Reverse the two and `ParseIntPipe` rejects the missing value before the default is ever applied. ## Traps worth knowing - **The empty string.** `?page=` delivers `''`, which is not `null` or `undefined`, so `DefaultValuePipe` passes it on and `ParseIntPipe` answers 400. If an empty value should mean "use the default", that needs a small custom pipe. - **A global `ValidationPipe` runs first.** Global pipes run before parameter pipes. With a global `ValidationPipe({ transform: true })` and the parameter typed `number`, that pipe converts the named query value with unary plus, so `''` arrives at `DefaultValuePipe` as `0`, which is not missing, and the handler gets page `0`. - **Decimal input.** `ParseIntPipe` never truncates; use `ParseFloatPipe` when fractions are legal. ## Changing the error Each built-in parse pipe accepts: - `errorHttpStatusCode`, for example `HttpStatus.NOT_ACCEPTABLE` to answer 406 instead of 400; - `exceptionFactory`, a function that receives the error message string and returns the exception to throw. Without either, a rejected `?page=abc` produces the standard body of a `BadRequestException`: ```json { "statusCode": 400, "message": "Validation failed (numeric string is expected)", "error": "Bad Request" } ``` Unlike `ValidationPipe`, whose `message` is an array of constraint messages, a parse pipe's `message` is a single string. A team that wants one error shape for every input failure therefore has to pass the same `exceptionFactory` to the parse pipes it binds, or normalise the body later in an exception filter. ## The sibling Parse* pipes The same binding style and the same `optional` behaviour apply across the family: - **`ParseFloatPipe`** accepts decimal numbers. - **`ParseBoolPipe`** accepts only `'true'`, `'false'` or real booleans, and otherwise fails with `Validation failed (boolean string is expected)`. - **`ParseUUIDPipe`** accepts a UUID of versions 1 to 8, plus the Nil and Max UUIDs, unless you pass `version` (for example `'4'`). A value that is not a string, including a missing one without `optional`, fails with `The value passed as UUID is not a string`. - **`ParseEnumPipe`** needs the enum object as its first constructor argument and throws at construction without it; numeric members also match their string form, since route values are strings. - **`ParseArrayPipe`** splits a delimited string (`separator`) and can validate or convert each element (`items`). - **`ParseDatePipe`** turns a value into a `Date`.

  • Why does ?page= fail even with new DefaultValuePipe(1) in front of ParseIntPipe?
    `DefaultValuePipe` replaces only `null`, `undefined` or a `NaN` number. An empty query value arrives as the empty string, which it passes on unchanged, and `ParseIntPipe` rejects `''` because it is not an integer string. Treating an empty value as missing takes a small custom pipe placed before `DefaultValuePipe`.
  • With a global ValidationPipe({ transform: true }), what does @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number give for ?page=?
    Page `0`. Global pipes run before parameter pipes, and `ValidationPipe` with `transform` converts a named query value typed `number` using unary plus, which turns `''` into `0`. `DefaultValuePipe` sees `0`, not a missing value, and `ParseIntPipe` accepts the number `0`.

  • ParseIntPipe lets a missing query parameter through as undefined by default
  • ParseIntPipe truncates '4.2' to 4 the way parseInt does
  • DefaultValuePipe can go after ParseIntPipe because pipe order does not matter
  • DefaultValuePipe also replaces the empty string sent by ?page=
  • ParseEnumPipe can check values without being given the enum