0
0
NestJSframework~5 mins

Default value pipe in NestJS

Choose your learning style9 modes available
Introduction

The Default value pipe helps set a fallback value when no input is provided. It keeps your app working smoothly without errors.

When a user might skip sending a value in a request.
When you want to ensure a variable always has a value.
When handling optional query parameters in APIs.
When you want to avoid manual checks for undefined or null.
When you want to simplify controller code by setting defaults early.
Syntax
NestJS
new DefaultValuePipe(defaultValue)

The defaultValue is the value used if the input is missing or undefined.

This pipe can be used in controller method parameters to provide default values automatically.

Examples
Sets the default page number to 1 if no page query parameter is sent.
NestJS
@Query('page', new DefaultValuePipe(1)) page: number
Defaults the sort order to 'asc' when the sort parameter is missing.
NestJS
@Query('sort', new DefaultValuePipe('asc')) sortOrder: string
Uses 'unknown' as the default id if none is provided in the route.
NestJS
@Param('id', new DefaultValuePipe('unknown')) id: string
Sample Program

This controller method uses DefaultValuePipe to set default values for 'limit' and 'offset' query parameters. If the client does not send these, the defaults 10 and 0 are used.

NestJS
import { Controller, Get, Query, DefaultValuePipe } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get()
  getItems(
    @Query('limit', new DefaultValuePipe(10)) limit: number,
    @Query('offset', new DefaultValuePipe(0)) offset: number
  ) {
    return `Limit is ${limit}, Offset is ${offset}`;
  }
}
OutputSuccess
Important Notes

DefaultValuePipe only sets the value if the input is undefined or missing, not if it is null or empty string.

You can combine DefaultValuePipe with other pipes like ParseIntPipe to validate and convert input.

Summary

DefaultValuePipe sets fallback values for missing inputs.

It simplifies controller code by avoiding manual checks.

Use it with query, param, or body decorators to handle optional data.