NestJS Decorators Reference
Complete NestJS decorator reference: controller setup, route decorators, parameter extraction, pipe validation, and custom decorators.
1. Controller & Route Decorators
import {
Controller, Get, Post, Put, Patch, Delete,
Param, Body, Query, Headers, Req, Res,
HttpCode, HttpStatus, Header, Redirect,
UseGuards, UsePipes, UseInterceptors,
} from '@nestjs/common';
@Controller('articles') // prefix: /articles
export class ArticlesController {
@Get()
findAll(@Query() query: FindArticlesDto) { ... }
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) { ... }
@Post()
@HttpCode(HttpStatus.CREATED)
create(@Body() dto: CreateArticleDto) { ... }
@Put(':id')
update(@Param('id') id: string, @Body() dto: UpdateArticleDto) { ... }
@Patch(':id')
partialUpdate(@Param('id') id: string, @Body() dto: Partial<UpdateArticleDto>) { ... }
@Delete(':id')
@HttpCode(HttpStatus.NO_CONTENT)
remove(@Param('id') id: string) { ... }
@Get(':id/redirect')
@Redirect('https://example.com', 301)
redirect() {}
@Get('csv')
@Header('Content-Type', 'text/csv')
@Header('Content-Disposition', 'attachment; filename="articles.csv"')
exportCsv() { ... }
}
2. Parameter Decorators
@Get(':id')
async findOne(
@Param('id') id: string, // route param
@Param() params: Record<string, string>, // all route params
@Query('page') page: number, // single query param
@Query() queryAll: FindArticlesDto, // all query params
@Body() body: CreateArticleDto, // request body
@Body('title') title: string, // single body field
@Headers('authorization') auth: string, // single header
@Headers() headers: Record<string, string>, // all headers
@Req() request: Request, // full request object
@Res({ passthrough: true }) response: Response, // response (passthrough keeps NestJS control)
) { ... }
3. Validation with Pipes
import { IsString, IsInt, Min, IsOptional, IsEmail } from 'class-validator';
import { Transform, Type } from 'class-transformer';
export class CreateUserDto {
@IsString()
@Transform(({ value }) => value.trim())
name: string;
@IsEmail()
email: string;
@IsOptional()
@IsInt()
@Min(0)
@Type(() => Number)
age?: number;
}
// Apply ValidationPipe globally
// main.ts
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // strip unknown properties
forbidNonWhitelisted: true,
transform: true, // auto-transform query strings to types
transformOptions: { enableImplicitConversion: true },
}));
// Per-endpoint
@Post()
create(@Body(new ValidationPipe({ whitelist: true })) dto: CreateArticleDto) { ... }
4. Custom Parameter Decorators
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
// Extract current user from request
export const CurrentUser = createParamDecorator(
(data: string | undefined, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
const user = request.user;
return data ? user?.[data] : user;
},
);
// Extract IP address
export const ClientIp = createParamDecorator(
(_data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.headers['x-forwarded-for']?.split(',')[0] ?? request.ip;
},
);
// Usage
@Get('profile')
@UseGuards(JwtAuthGuard)
getProfile(
@CurrentUser() user: User,
@CurrentUser('email') email: string,
@ClientIp() ip: string,
) { ... }
5. Method & Class Decorators
import { UseGuards, UseInterceptors, UsePipes, UseFilters, SetMetadata, applyDecorators } from '@nestjs/common';
// Compose multiple decorators into one
export const Auth = (...roles: string[]) => applyDecorators(
SetMetadata('roles', roles),
UseGuards(JwtAuthGuard, RolesGuard),
ApiBearerAuth(), // Swagger
ApiUnauthorizedResponse({ description: 'Unauthorized' }),
);
// Usage
@Controller('admin')
export class AdminController {
@Get('users')
@Auth('admin') // applies all 4 decorators
getUsers() { ... }
}
6. Route Decorator Quick Reference
| Decorator | HTTP Method | Notes |
|---|---|---|
| @Get(path?) | GET | — |
| @Post(path?) | POST | — |
| @Put(path?) | PUT | — |
| @Patch(path?) | PATCH | — |
| @Delete(path?) | DELETE | — |
| @Head(path?) | HEAD | — |
| @Options(path?) | OPTIONS | — |
| @All(path?) | All methods | — |
| @HttpCode(n) | — | Override status code |
| @Header(k,v) | — | Set response header |
| @Redirect(url) | — | Redirect response |