Pipes & Validation
A pipe sits between the incoming request and your handler. It receives one argument — a route param, a query value, the body — and either transforms it (the string "42" becomes the number 42) or rejects it with an exception before the handler runs. Pipes are Nest's answer to the validation middleware you wrote in Express.
Built-in pipes
| Pipe | Turns | Rejects with 400 when… |
|---|---|---|
ParseIntPipe |
"42" → 42 |
not an integer string |
ParseFloatPipe |
"4.5" → 4.5 |
not a number |
ParseBoolPipe |
"true" → true |
not true/false |
ParseUUIDPipe |
checks format | not a UUID |
ParseEnumPipe |
checks membership | value not in the enum |
ParseArrayPipe |
"a,b" → ['a','b'] |
items fail validation |
DefaultValuePipe |
undefined → a default |
— |
ValidationPipe |
plain object → validated DTO instance | DTO rules fail |
@Get()
findAll(
@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number,
@Query('active', new DefaultValuePipe(true), ParseBoolPipe) active: boolean,
) {
return this.catsService.findAll({ page, active }); // real number and boolean
}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) { /* … */ }curl "http://localhost:3000/cats?page=2&active=false"
curl "http://localhost:3000/cats?page=two"
curl http://localhost:3000/cats/abc{"page":2,"active":false,"items":[]}
{"message":"Validation failed (numeric string is expected)","error":"Bad Request","statusCode":400}
{"message":"Validation failed (numeric string is expected)","error":"Bad Request","statusCode":400}
How a pipe works
A pipe is a class with a transform(value, metadata) method. Pipes listed together run left to right, each receiving the previous result. This playground recreates DefaultValuePipe and ParseIntPipe and chains them the way Nest does:
class BadRequestException extends Error {
readonly statusCode = 400;
}
interface PipeTransform<T = unknown, R = unknown> {
transform(value: T): R;
}
class DefaultValuePipe implements PipeTransform {
constructor(private readonly fallback: unknown) {}
transform(value: unknown) {
return value === undefined || value === null || value === '' ? this.fallback : value;
}
}
class ParseIntPipe implements PipeTransform {
transform(value: unknown): number {
if (typeof value === 'number' && Number.isInteger(value)) return value;
if (typeof value !== 'string' || !/^-?\d+$/.test(value)) {
throw new BadRequestException('Validation failed (numeric string is expected)');
}
return Number.parseInt(value, 10);
}
}
function runPipes(value: unknown, pipes: PipeTransform[]) {
return pipes.reduce((v, pipe) => pipe.transform(v), value);
}
const pagePipes = [new DefaultValuePipe(1), new ParseIntPipe()];
for (const raw of ['3', undefined, '-1', '2.5', 'two']) {
try {
const page = runPipes(raw, pagePipes);
console.log(JSON.stringify(raw), '->', page, typeof page);
} catch (e) {
const err = e as BadRequestException;
console.log(JSON.stringify(raw), '->', err.statusCode, err.message);
}
}"3" -> 3 number
undefined -> 1 number
"-1" -> -1 number
"2.5" -> 400 Validation failed (numeric string is expected)
"two" -> 400 Validation failed (numeric string is expected)
Validating bodies with DTOs
For request bodies, Nest uses DTO classes (Data Transfer Objects) decorated with rules from the class-validator package, plus class-transformer to turn the plain JSON into an instance:
npm install class-validator class-transformeradded 4 packages, and audited 712 packages in 3s
found 0 vulnerabilities
// src/cats/dto/create-cat.dto.ts
import { IsInt, IsOptional, IsString, Length, Max, Min } from 'class-validator';
export class CreateCatDto {
@IsString()
@Length(1, 40)
name: string;
@IsInt()
@Min(0)
@Max(30)
age: number;
@IsOptional()
@IsString()
breed?: string;
}Turn validation on for the whole app in main.ts:
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // strip properties without decorators
forbidNonWhitelisted: true, // …or reject them with 400 instead
transform: true, // give handlers real DTO instances and convert primitive params
}),
);Now create(@Body() dto: CreateCatDto) only ever receives valid data:
curl -X POST localhost:3000/cats -H "Content-Type: application/json" -d '{"name":"Pixel","age":1}'
curl -X POST localhost:3000/cats -H "Content-Type: application/json" -d '{"name":"Pixel","age":-2}'
curl -X POST localhost:3000/cats -H "Content-Type: application/json" -d '{"name":"Pixel","age":1,"isAdmin":true}'{"id":2,"name":"Pixel","age":1}
{"message":["age must not be less than 0"],"error":"Bad Request","statusCode":400}
{"message":["property isAdmin should not exist"],"error":"Bad Request","statusCode":400}
Note that message is an array for ValidationPipe errors — one entry per failed rule — so a client can show every problem at once. And whitelist protects you from the mass-assignment problem you met in the CRUD lesson.
Reusing DTOs
@nestjs/mapped-types (or @nestjs/swagger, which re-exports the same helpers) derives new DTOs from existing ones, keeping the validation rules:
export class UpdateCatDto extends PartialType(CreateCatDto) {} // every field optional
export class CatNameDto extends PickType(CreateCatDto, ['name']) {} // only name
export class CatWithoutAgeDto extends OmitType(CreateCatDto, ['age']) {}A custom pipe
Any class implementing PipeTransform is a pipe. Here is a pipe that trims and lowercases a slug and rejects invalid characters:
@Injectable()
export class SlugPipe implements PipeTransform<string, string> {
transform(value: string) {
const slug = value.trim().toLowerCase();
if (!/^[a-z0-9-]+$/.test(slug)) throw new BadRequestException('Invalid slug');
return slug;
}
}
@Get('by-slug/:slug')
findBySlug(@Param('slug', SlugPipe) slug: string) { /* … */ }| Where to bind a pipe | Scope |
|---|---|
@Param('id', ParseIntPipe) |
one parameter |
@UsePipes(MyPipe) on a method or controller |
all parameters of that handler/controller |
app.useGlobalPipes(...) or { provide: APP_PIPE, useClass: ValidationPipe } |
the whole app |
Tip: Prefer registering the global
ValidationPipevia theAPP_PIPEprovider inAppModule— then it also applies in e2e tests that build the app from the module, not just whenmain.tsruns.
Test yourself
What does @Param('id', ParseIntPipe) id: number do for the URL /cats/abc?
- Passes
NaNto the handler - Passes the string 'abc'
- Responds 400 before the handler runs
- Responds 404
With ValidationPipe({ whitelist: true }), what happens to a body property that has no validation decorator in the DTO?
- It is kept
- It is stripped
- The server crashes
- It is converted to a string
In which order do the pipes in @Query('page', new DefaultValuePipe(1), ParseIntPipe) run?
- ParseIntPipe, then DefaultValuePipe
- DefaultValuePipe, then ParseIntPipe
- In parallel
- Only the last one runs