19

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 ?

moh
  • 205
  • 1
  • 3
  • 6

2 Answers2

36

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;
  },
);
Naor Levi
  • 1,713
  • 1
  • 13
  • 27
0

Hi I was working with Typescript and graphql so the above solution didn't work for me. Perhaps you should see this solution.

NestJS custom decorator returns undefined

Ernesto
  • 41
  • 6