How to get JWT payload from different key rather than req.user in NestJS

697 Views Asked by At

The way to get payload after the guard is like what this tutorial mentioned.

@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@Request() req) {
  return req.user;
}

Basically, you can access the payload with the object key user in the request.

But I'd like to know how to store this payload in another key. Is it possible?

1

There are 1 best solutions below

0
On

you should define a decorator file for getting user:

export const getUser = createParamDecorator (
    ( data:unknown , ctx:ExecutionContext) => {
        const request=ctx.switchToHttp().getRequest();
        return request.user;
    }
)

and use it in controller like this:

@UseGuards(JwtAuthGuard)
@Get('profile')
getProfile(@getUser() user:User) {

}

you can find documentation here: https://docs.nestjs.com/custom-decorators