Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 42 ยท The Request Pipeline

Custom Decorators

Write your own NestJS decorators: createParamDecorator for @CurrentUser, SetMetadata wrappers such as @Roles, and applyDecorators to bundle several decorators into one.

By now you have used many decorators that ship with Nest: @Get(), @Body(), @UseGuards(), @Roles() from the guards lesson. A decorator is just a function that attaches information to a class, a method or a parameter. Nest reads that information when the app starts or when a request arrives. Once you see that, writing your own is easy, and it is one of the best ways to keep controllers short and readable.

Custom decorators solve three recurring problems. First, handlers keep digging the same value out of the request, such as the logged-in user. Second, the same three decorators get stacked on many routes (@UseGuards, @Roles, @ApiBearerAuth). Third, rules such as "only admins" should read as one word, not as plumbing. You will meet three tools for these: createParamDecorator, SetMetadata wrappers and applyDecorators.

The Nest code below is read-only (it needs npm and TypeScript decorators). The runnable stand-ins use plain functions to show what Nest does with the decorators you write, and say clearly where they are simplified.

Three kinds of custom decorator

Parameter Pulls a value out of the request.
Metadata Tags a route for a guard to read.
Composed Bundles several decorators into one.

Each one removes repetition from your controllers.

1 / 2

A parameter decorator: @CurrentUser

Suppose an authentication guard has verified a token and stored the user on request.user. Without a custom decorator, every handler reads it from the raw request:

TypeScript
@Get('me')
profile(@Req() req: Request) {
  return req['user'];
}

This works, but it ties the handler to the Express request object (which also makes it awkward on Fastify or in a microservice), and it is untyped. A parameter decorator fixes both:

TypeScript
import { createParamDecorator, ExecutionContext } from '@nestjs/common';

export const CurrentUser = createParamDecorator(
  (field: keyof AuthUser | undefined, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user: AuthUser = request.user;
    return field ? user?.[field] : user;
  },
);

createParamDecorator takes a factory with two arguments. The first (field) is whatever you pass in the decorator call, so @CurrentUser('id') hands you 'id'. The second is the execution context, the same object guards receive. Whatever the factory returns becomes the value of the handler parameter:

TypeScript
@UseGuards(AuthGuard)
@Get('me')
profile(@CurrentUser() user: AuthUser) {
  return user;
}

@Delete('me')
remove(@CurrentUser('id') userId: number) {
  return this.users.remove(userId);
}

Two details matter. The decorator only reads; it does not authenticate. If no guard ran, request.user is undefined, so keep the guard on the route. And the factory runs per request, after guards and interceptors have run, just before the handler is called, because that is when Nest resolves parameter values.

Use ctx.getType() when the same decorator must work for HTTP, GraphQL and WebSocket handlers. For GraphQL you need GqlExecutionContext.create(ctx).getContext().req instead of switchToHttp(), which is why many GraphQL projects ship a second decorator with the same name.

Pipes still work on custom decorators

Custom parameter decorators take part in the normal pipe flow. You can validate the value they return by passing a pipe, for example @CurrentUser(new ValidationPipe({ validateCustomDecorators: true })) user: AuthUser. By default ValidationPipe skips custom decorators, so set validateCustomDecorators: true if you want a DTO class to be checked. Often you do not need it, because the guard already produced a trusted object.

Running a param decorator by hand

Here is a stand-in that mimics the mechanism. The "controller" records, for each handler, which parameter factories to call. A tiny dispatcher builds the arguments from a fake request, exactly as Nest does just before calling your method. This is not Nest's real implementation, but the idea (a factory plus a context, called per request) is the same.

Node.js Param decorators as factories

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line shows why a guard must stay on the route: the decorator happily returns undefined when nothing set the user.

Metadata decorators: @Roles and friends

A decorator does not have to touch the request at all. It can simply tag a route, and a guard or interceptor reads the tag later. Nest's SetMetadata(key, value) stores a value on a class or method, and the Reflector reads it back. You saw this with @Roles in the guards lesson. Wrapping SetMetadata in your own decorator gives you a typed, memorable name and hides the string key:

TypeScript
import { SetMetadata } from '@nestjs/common';

export const IS_PUBLIC = 'isPublic';
export const Public = () => SetMetadata(IS_PUBLIC, true);

export const ROLES_KEY = 'roles';
export const Roles = (...roles: Role[]) => SetMetadata(ROLES_KEY, roles);

A guard reads the tags. getAllAndOverride looks at the handler first and then at the class, so a method-level tag wins:

TypeScript
@Injectable()
export class RolesGuard implements CanActivate {
  constructor(private reflector: Reflector) {}

  canActivate(context: ExecutionContext): boolean {
    const required = this.reflector.getAllAndOverride<Role[]>(ROLES_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (!required) return true;
    const { user } = context.switchToHttp().getRequest();
    return required.includes(user?.role);
  }
}

If you would rather not repeat the string key and the type argument, Reflector.createDecorator<Role[]>() builds a typed decorator and a matching reflector.get(Roles, handler) call in one step. The result is the same: metadata, then a guard that interprets it.

Bundling decorators with applyDecorators

Look at a typical admin route in a documented API:

TypeScript
@Get('reports')
@UseGuards(AuthGuard, RolesGuard)
@Roles(Role.Admin)
@ApiBearerAuth()
@ApiUnauthorizedResponse({ description: 'Missing or invalid token' })
@ApiForbiddenResponse({ description: 'Admins only' })
reports() { /* ... */ }

Five decorators describe one idea: "admins only". Copying them to twenty routes invites mistakes, such as forgetting the guard on one of them. applyDecorators combines several decorators into one:

TypeScript
import { applyDecorators, UseGuards } from '@nestjs/common';

export function AdminOnly() {
  return applyDecorators(
    UseGuards(AuthGuard, RolesGuard),
    Roles(Role.Admin),
    ApiBearerAuth(),
    ApiUnauthorizedResponse({ description: 'Missing or invalid token' }),
    ApiForbiddenResponse({ description: 'Admins only' }),
  );
}

@Get('reports')
@AdminOnly()
reports() { /* ... */ }

The security rule now has a name, lives in one file, and a code review can search for @AdminOnly to find every protected route. Note that applyDecorators works with decorators that can sit on classes or methods, so it fits UseGuards, SetMetadata, UseInterceptors and the Swagger decorators. It does not produce parameter decorators; for those you use createParamDecorator.

Composing metadata and guards by hand

The stand-in below builds the same three pieces without Nest: a SetMetadata that writes to a map, a Reflector that reads it with handler-then-class lookup, a roles guard, and an applyDecorators that runs several decorators on one target. The decorators here receive a plain object that represents a route.

Node.js Metadata, a roles guard and applyDecorators

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Sam, a staff member, is blocked from both routes because AdminOnly replaced the class-level staff tag on list, and purge carries its own admin tag. The key lesson is the lookup order: handler first, class second.

Good habits for custom decorators

  • Name them for intent. @Public() and @AdminOnly() read like policy; @Meta('x', true) does not.
  • Keep factories pure and cheap. A param decorator runs on every request. Do not call the database in it; use a guard or pipe for that.
  • Do not hide authentication in a param decorator. Let a guard reject the request, and let the decorator only read what the guard prepared.
  • Put shared decorators in common/decorators/, as described in Project Structure and the CLI.
  • Type the result. Declare AuthUser once and use it in the parameter, so a refactor shows up at compile time.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the first argument of a createParamDecorator factory contain?

    The factory receives the decorator's own argument first and the ExecutionContext second. The context is how you reach the request.
  2. 2. You apply @Roles('staff') to a controller class and @Roles('admin') to one of its methods. A guard uses getAllAndOverride with [handler, class]. Which roles are required for that method?

    getAllAndOverride returns the first value it finds, checking the handler before the class, so the method-level tag wins. getAllAndMerge would combine them.
  3. 3. Which of these can applyDecorators NOT build?

    applyDecorators combines class and method decorators. A parameter value needs createParamDecorator.
  4. 4. A route uses @CurrentUser() but no guard. What does the handler receive when the request has no user?

    Decorators do not authenticate. Keep an authentication guard on the route so unauthenticated requests are rejected before the handler runs.

Summary

  • A decorator is a function that attaches information; Nest reads it at startup or per request.
  • createParamDecorator((data, ctx) => ...) builds parameter decorators such as @CurrentUser('id'); the factory runs per request and should only read what a guard prepared.
  • SetMetadata wrapped in your own decorator (@Roles, @Public) tags routes, and a guard reads the tags with Reflector.getAllAndOverride, handler first and class second.
  • applyDecorators bundles class and method decorators (guards, metadata, Swagger) into one named rule such as @AdminOnly().
  • Custom decorators never replace guards: they describe or read, guards decide.

Next, learn how to receive files from clients in File Uploads with Multer.