Krissh
Krissh

Reputation: 89

nestjs logger logs undefined although the value is defined

I'm trying to create a custom @CurrentUser decorator to get the req.user set by the Passport JWT strategy. Confusingly, I get undefined when logging the req.user using NestJs's built-in logger and also while using the decorator anywhere to get the user and perform any operations. But when I log the req.user object using the javascript 'console.log' method, or when I send the req.user directly as response, the expected object is logged/ returned correctly.

What am I doing wrong?

current-user.decorator.ts:

import { createParamDecorator, ExecutionContext, Logger } from '@nestjs/common';
import { AuthPayload } from '../token/token.strategy';

const CurrentUser = createParamDecorator(
  async (_data: never, context: ExecutionContext): AuthPayload => {
    const req = context.switchToHttp().getRequest();

    Logger.verbose(req.user, 'CurrentUser'); // undefined
    console.log(req.user); // { id: ....., email: ... }

    return req.user;
  }
);

TokenStrategy.ts (JWT Strategy implementation):

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { AuthConfig } from '../../../config';
import { User } from '../../user/user.entity';

export type AuthPayload = Pick<User, 'id' | 'avatarUrl' | 'displayName' | 'email'>;

@Injectable()
export class AuthTokenStrategy extends PassportStrategy(Strategy) {
  constructor(configService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get<AuthConfig>('auth').jwt.secret,
    });
  }

  async validate(payload: AuthPayload) {
    return payload;
  }
}

UPDATE:

RESOLVED. So the problem was actually a mixup of my logger (winston) and a missing await. It took me 2 days to figure this out completely. VSCode debugger was of great help for finding this. So if you are facing a similar problem, make sure you're awaiting your promises properly. If you are using winston logger, DITCH it! Even if you don't face issues now, you're gonna scratch your head sometime soon.

Upvotes: 1

Views: 1172

Answers (0)

Related Questions