02 / 07

How do you create a custom parameter decorator in NestJS?

Use createParamDecorator which receives a factory function with (data, ctx) arguments. The data argument is whatever is passed into the decorator at usage time, and ctx is the ExecutionContext providing access to the request, response, and other context.

Custom @CurrentUser() decorator
Key points:
  1. 1

    createParamDecorator takes a factory function that receives data and ctx.

  2. 2

    data is the argument passed to the decorator at the call site.

  3. 3

    ctx.switchToHttp().getRequest() gives the underlying HTTP request.

  4. 4

    Custom param decorators can be combined with pipes for validation.