How do you create a custom decorator in NestJS?
Answer
NestJS allows creating custom parameter decorators to extract and transform data from the request. Use createParamDecorator: export const CurrentUser = createParamDecorator((data: unknown, ctx: ExecutionContext) => { const request = ctx.switchToHttp().getRequest(); return request.user; });. Then use it in a controller: @Get('profile') getProfile(@CurrentUser() user: User) { return user; }. This is cleaner than repeatedly writing @Req() req: Request; const user = req.user;. Custom decorators improve readability and allow logic reuse. You can also create class/method decorators using SetMetadata to attach custom metadata that Guards can read via Reflector.
Previous
What is the @nestjs/swagger module?
Next
How does NestJS dependency injection scoping work?