0
0
NestjsConceptBeginner · 3 min read

What is Pipe in NestJS: Explanation and Example

In NestJS, a pipe is a class that processes input data before it reaches the route handler. Pipes can transform data or validate it, ensuring the input is correct and safe to use.
⚙️

How It Works

Think of a pipe in NestJS like a checkpoint on a road. When data comes into your application, it passes through this checkpoint where it can be checked or changed before continuing. This helps keep your app safe and clean.

Technically, a pipe is a class that implements a transform method. This method receives the input data and can either return the data as is, modify it, or throw an error if the data is invalid. NestJS runs pipes automatically before your controller methods get called.

💻

Example

This example shows a simple pipe that converts a string input to a number and checks if it is a valid number. If not, it throws an error.

typescript
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common';

@Injectable()
export class ParseIntPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Validation failed: Not a number');
    }
    return val;
  }
}

// Usage in a controller method
import { Controller, Get, Param } from '@nestjs/common';

@Controller('items')
export class ItemsController {
  @Get(':id')
  getItem(@Param('id', ParseIntPipe) id: number) {
    return `Item id is ${id}`;
  }
}
Output
If you call GET /items/123, the output is: "Item id is 123". If you call GET /items/abc, it returns a 400 error with message "Validation failed: Not a number".
🎯

When to Use

Use pipes when you want to check or change incoming data before your app uses it. For example, you can:

  • Validate user input to prevent errors or security issues.
  • Transform data types, like converting strings to numbers or dates.
  • Sanitize data to remove unwanted characters.

This keeps your controller code simple and focused on business logic, while pipes handle data safety and correctness.

Key Points

  • Pipes run before route handlers to process input data.
  • They can transform data or validate it.
  • Throwing an error in a pipe stops the request with a clear message.
  • Built-in pipes exist, but you can create custom ones.
  • Use pipes to keep your app safe and your code clean.

Key Takeaways

Pipes in NestJS process and validate input data before it reaches your controller.
They help transform data types and ensure data correctness.
Throwing errors in pipes stops bad data from reaching your app logic.
Custom pipes let you handle specific validation or transformation needs.
Using pipes keeps your code clean and your app secure.