0
0
NestJSframework~5 mins

Pipe binding (parameter, method, controller, global) in NestJS

Choose your learning style9 modes available
Introduction

Pipes help process and validate data before it reaches your code. Binding pipes lets you control where and how this happens.

When you want to check or change data for a single parameter in a request.
When you want to apply data validation or transformation to all parameters in a method.
When you want all methods in a controller to use the same data processing rules.
When you want to apply a pipe globally to all incoming requests in your app.
Syntax
NestJS
1. Parameter binding:
@Get(':id')
method(@Param('id', Pipe) id: string) {}

2. Method binding:
@UsePipes(Pipe)
method() {}

3. Controller binding:
@UsePipes(Pipe)
@Controller()
class MyController {}

4. Global binding:
app.useGlobalPipes(new Pipe());

Use @UsePipes() decorator for method and controller binding.

Parameter binding applies pipe only to that parameter.

Examples
This converts the 'id' parameter to a number using ParseIntPipe.
NestJS
@Get(':id')
getById(@Param('id', ParseIntPipe) id: number) {
  return id;
}
This validates the whole body data for the create method.
NestJS
@UsePipes(ValidationPipe)
@Post()
create(@Body() data: CreateDto) {
  return data;
}
All methods in UserController will validate input data.
NestJS
@UsePipes(ValidationPipe)
@Controller('users')
class UserController {
  @Post()
  create(@Body() data: CreateUserDto) {
    return data;
  }
}
This applies validation to all requests in the app.
NestJS
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
Sample Program

This example shows pipe binding at all levels: parameter (ParseIntPipe), controller (ValidationPipe), and global (ValidationPipe in main).

NestJS
import { Controller, Get, Param, UsePipes, ValidationPipe, ParseIntPipe } from '@nestjs/common';

@Controller('items')
@UsePipes(new ValidationPipe())
export class ItemsController {
  @Get(':id')
  getItem(@Param('id', ParseIntPipe) id: number) {
    return { itemId: id };
  }
}

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe());
  await app.listen(3000);
}
bootstrap();
OutputSuccess
Important Notes

Pipes run in this order: global, controller, method, then parameter.

Parameter pipes override method or controller pipes for that parameter.

Use pipes to keep your code clean by handling validation and transformation outside your main logic.

Summary

Pipes process data before your code uses it.

You can bind pipes to parameters, methods, controllers, or globally.

Binding location controls how widely the pipe applies.