NestJS – current auth user but not via decorator

I create belowed decorator to get current logged in to the system user,

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

but I do not want to use this because i need to use in any of my controller
which is a bit troublesome for me because some functions are optional, i.e. both for the logged in user and the non logged in user,

so, how can I get current logged in user in my service in functions when i want to get current user instead of all via decorator in controller?

thanks for any help

2 thoughts on “NestJS – current auth user but not via decorator”

  1. You’d have to make a custom provider and inject the request into it. Something like this

    {
      provider: 'CURRENT_USER',
      inject: [REQUEST],
      useFactory: (req: Request) => {
        return req.user;
      },
      scope: Scope.REQUEST,
    }
    

    (REQUEST is injected from @nestjs/core)

    Then the user can be injected into the service with @Inject('CURRENT_USER'). Keep in mind, this will make the service REQUEST scoped, and by scope hierarchy it will make whatever you inject the service into REQUEST scoped.

    Edit 2/15/21

    An example of this module could look something like this:

    @Module({
      providers: [{
        provider: 'CURRENT_USER',
        inject: [REQUEST],
        useFactory: (req: Request) => {
          return req.user;
        },
        scope: Scope.REQUEST,
      }],
      exports: ['CURRENT_USER'],
    })
    export class CurrentUserModule {}
    

    And now in whatever module that has the service that needs the current user you do

    @Module({
      imports: [CurrentUserModule],
      providers: [ServiceThatNeedsUser],
    })
    export class ModuleThatNeedsUser {}
    

    and in the service:

    @Injectable()
    export class ServiceThatNeedsUser {
      constructor(@Inject('CURRENT_USER') private readonly user: UserType) {}
    
      // rest of class implementation
    }
    
    Reply

Leave a Comment