Search code examples
nestjsnestjs-passport

how to get user data with req.user on decorator in nest js


I created the authentication ( jwt ) and the process is done properly.

I can access the user's information using the following code, but I can't get the user's information using the decorator!

controller :

@Post('/me/info')
  @UseGuards(AuthGuard())
  myInfo(
    @GetUser() user,
    @Req() req,
  ) {
    console.log(user); // undefined 
    console.log(req.user); // get user data object
  }

my decorator is:

import { createParamDecorator } from '@nestjs/common';
import { User } from './user.entity';

export const GetUser = createParamDecorator((data, req): User => {
  return req.user;
});

what is my code problem ?


Solution

  • The problem is in createParamDecorator.

    An excerpt from the official manual on custom decorators:

    import { createParamDecorator, ExecutionContext } from '@nestjs/common';
    
    export const User = createParamDecorator(
      (data: unknown, ctx: ExecutionContext) => {
        const request = ctx.switchToHttp().getRequest();
        return request.user;
      },
    );