Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 42 ยท The Request Pipeline

Pipes and Validation

Learn NestJS pipes: ParseIntPipe, ValidationPipe with class-validator DTOs, whitelist and transform options, and how to write custom pipes.

A pipe is a class that receives an argument just before your route handler runs and does one of two things with it: it transforms the value (a string "42" becomes the number 42), or it validates it and throws an exception if it is not acceptable. Pipes are how a Nest controller can assume that id really is a number and body.email really looks like an email.

Pipes run late in the pipeline, after middleware and guards and just before the handler, so they only spend work on requests that are allowed through. When a pipe throws, the handler never runs and an exception filter turns the error into a response, usually 400 Bad Request.

The real Nest code here is read-only (it needs Node, npm and the class-validator and class-transformer packages). The runnable parts at the end are stand-ins written in plain JavaScript that mimic what those libraries do, so you can see the logic of validation and transformation without installing anything.

Two jobs for a pipe

Transform Turn "42" into 42.
Validate Reject bad input early.

Both happen before your handler runs.

1 / 2

Built-in parse pipes

Everything from the URL arrives as a string. A parse pipe converts it and rejects anything that cannot be converted:

TypeScript
import { Controller, Get, Param, ParseIntPipe, Query, DefaultValuePipe } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.cats.find(id); // id is a real number here
  }

  @Get()
  list(
    @Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
    @Query('limit', new DefaultValuePipe(20), ParseIntPipe) limit: number,
  ) {
    return this.cats.list(page, limit);
  }
}

A request to GET /cats/abc is answered with a 400 response whose message says that a numeric string is expected, and findOne is never called. There are siblings for other types: ParseFloatPipe, ParseBoolPipe, ParseArrayPipe, ParseUUIDPipe, ParseEnumPipe and ParseFilePipe.

You pass either the class (ParseIntPipe, Nest creates it) or an instance (new ParseIntPipe({ errorHttpStatusCode: 406 })) when you need options. Several pipes listed on one argument run left to right, so DefaultValuePipe first and ParseIntPipe second means a missing page becomes 1, then is parsed.

DTOs with class-validator

For request bodies, you describe the shape with a DTO (data transfer object) class and put validation rules on its properties with decorators from the class-validator package:

TypeScript
import { IsEmail, IsInt, IsOptional, IsString, Min, MinLength } from 'class-validator';

export class CreateUserDto {
  @IsString()
  @MinLength(3)
  name: string;

  @IsEmail()
  email: string;

  @IsInt()
  @Min(18)
  @IsOptional()
  age?: number;
}

Then enable ValidationPipe. The usual place is main.ts, so it applies to every route:

TypeScript
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
  }),
);

and the controller simply declares the type:

TypeScript
@Post()
create(@Body() dto: CreateUserDto) {
  return this.users.create(dto);
}

Nest reads the parameter's TypeScript type at runtime (this relies on emitDecoratorMetadata, which the project template enables), runs the rules, and on failure responds with 400 and a body like this:

JSON
{
  "message": ["name must be longer than or equal to 3 characters", "email must be an email"],
  "error": "Bad Request",
  "statusCode": 400
}

DTOs have to be classes, not interfaces or type aliases. Interfaces disappear when TypeScript compiles, so ValidationPipe would have no type to read and nothing to validate with.

The options you will actually use

Option What it does
whitelist: true Removes properties that have no validation decorator. Defends against mass assignment (a client sending isAdmin: true)
forbidNonWhitelisted: true With whitelist, rejects the request instead of silently stripping extra properties
transform: true Returns an instance of the DTO class (not a plain object) and converts primitives in @Param() and @Query() to the declared type
transformOptions: { enableImplicitConversion: true } Converts types without needing @Type() decorators; handy for query DTOs, but convert deliberately
stopAtFirstError: true Reports one error per property instead of all
disableErrorMessages: true Hides details in production if you prefer terse errors

Without transform: true the value you receive is still the plain parsed JSON that passed validation; it is not an instance of CreateUserDto. That matters if your DTO has methods or if you want @Query('page') page: number to be a real number.

Nested objects need two decorators: @ValidateNested() from class-validator and @Type(() => AddressDto) from class-transformer, so the transformer knows which class to build for the inner object.

For update endpoints, the @nestjs/mapped-types package offers PartialType(CreateUserDto), PickType and OmitType, which reuse the same rules without copy-pasting them. The security side of whitelisting is revisited in Security and Hardening.

Writing a custom pipe

A pipe implements PipeTransform. Whatever transform returns becomes the argument; throwing an exception aborts the request:

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

@Injectable()
export class TrimPipe implements PipeTransform<unknown, unknown> {
  transform(value: unknown, metadata: ArgumentMetadata) {
    if (typeof value === 'string') return value.trim();
    return value;
  }
}

@Injectable()
export class PositiveIntPipe implements PipeTransform<string, number> {
  transform(value: string) {
    const n = Number(value);
    if (!Number.isInteger(n) || n <= 0) {
      throw new BadRequestException('Expected a positive integer');
    }
    return n;
  }
}

ArgumentMetadata tells the pipe where the value came from: type is 'body', 'query', 'param' or 'custom', metatype is the declared TypeScript type, and data is the name you passed to the decorator (such as 'id').

Pipes can be bound at several levels: on one argument (@Param('id', PositiveIntPipe)), on a method or a whole controller with @UsePipes(), or globally with app.useGlobalPipes(). To use dependency injection inside a global pipe, register it as a provider with the APP_PIPE token instead. Custom Providers explains that form.

Stand-in: a validator and transformer in JavaScript

This is not class-validator. It is a few dozen lines that follow the same ideas: rules per property, a whitelist that strips unknown keys, optional properties, and messages shaped like class-validator's. The real library does much more (nested validation, groups, custom decorators, async rules).

JS A mini ValidationPipe

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first call shows whitelist quietly dropping isAdmin. The second turns the same extra property into an error. The third collects every problem at once, like the default ValidationPipe does.

Stand-in: parse pipes and a pipe chain

The second stand-in shows the transformation side: pipes as small functions that run in order on one argument, with the metadata object a real pipe would receive.

JS Pipes as a chain of functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The missing page was filled by the default before it was parsed, which is exactly why the order of pipes in the decorator matters.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does @Param('id', ParseIntPipe) do when the URL is /cats/abc?

    ParseIntPipe refuses values that are not numeric strings and responds with 400 before the handler runs.
  2. 2. Why must a DTO used with ValidationPipe be a class and not an interface?

    Decorators and the emitted type metadata live on real classes. An interface leaves nothing behind at runtime.
  3. 3. A client sends { "name": "Ada", "isAdmin": true } and your DTO has no isAdmin property. Which setting removes isAdmin silently?

    whitelist strips properties that have no validation decorator. Adding forbidNonWhitelisted would reject the request instead.
  4. 4. Which option makes @Query('page') page: number arrive as a real number and the body as an instance of the DTO class?

    Without transform, validated data stays a plain object and query values stay strings.
  5. 5. For @Query('page', new DefaultValuePipe(1), ParseIntPipe), in what order do the pipes run?

    Pipes on one argument run in the order listed, so a missing value is replaced by the default and then parsed.

Summary

  • Pipes transform or validate handler arguments right before the handler runs; a thrown exception skips the handler.
  • Built-in parse pipes (ParseIntPipe, ParseUUIDPipe, ...) convert and check path and query strings; DefaultValuePipe fills gaps.
  • For bodies, write DTO classes with class-validator decorators and enable ValidationPipe, usually globally.
  • Use whitelist (and often forbidNonWhitelisted) against mass assignment, and transform to get class instances and typed query values.
  • A custom pipe implements PipeTransform and receives the value plus ArgumentMetadata.

Next, decide who may call each route in Guards and Authorization.