0
0
NestJSframework~5 mins

Custom pipes in NestJS

Choose your learning style9 modes available
Introduction

Custom pipes let you change or check data before your code uses it. They help keep your app clean and safe.

You want to check if user input is correct before saving it.
You need to change data format, like turning a string into a number.
You want to block bad data early to avoid errors later.
You want to reuse the same data check in many places.
You want to keep your main code simple by moving data checks out.
Syntax
NestJS
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class CustomPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    // change or check value here
    return value; // return changed or original value
  }
}

The transform method runs automatically on data.

Throw BadRequestException to stop bad data.

Examples
This pipe changes a string to a number and stops if it is not a number.
NestJS
import { PipeTransform, BadRequestException } from '@nestjs/common';

export class ParseIntPipe implements PipeTransform {
  transform(value: any) {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Value must be a number');
    }
    return val;
  }
}
This pipe removes spaces from the start and end of a string.
NestJS
import { PipeTransform } from '@nestjs/common';

export class TrimPipe implements PipeTransform {
  transform(value: any) {
    if (typeof value === 'string') {
      return value.trim();
    }
    return value;
  }
}
Sample Program

This example shows a controller with a custom pipe that changes the query parameter id from a string to a number. If id is not a number, it stops the request with an error.

NestJS
import { Controller, Get, Query, UsePipes, PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
class ParseIntPipe implements PipeTransform {
  transform(value: any) {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Value must be a number');
    }
    return val;
  }
}

@Controller('items')
export class ItemsController {
  @Get()
  @UsePipes(new ParseIntPipe())
  getItem(@Query('id') id: number) {
    return `Item id is ${id}`;
  }
}
OutputSuccess
Important Notes

Always add @Injectable() to your custom pipe class.

Use pipes to keep your controller code clean and focused on business logic.

You can apply pipes globally, to controllers, or to specific routes.

Summary

Custom pipes let you check or change data before your code uses it.

They help catch errors early and keep your app safe.

You write a class with a transform method to make a custom pipe.