typescriptjwtnestjspassport.js

[NestJs]: JwtModule.register() not working


I'm using JwtModule in NestJs and it seems like that the register method does not set the secret property for my injected service. I get this error: enter image description here

Here's the code:

@Module({
  imports: [
    UserModule,
    PassportModule,
    JwtModule.register({
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '1w' },
    }),
  ],
  providers: [AuthService, BcryptService, LocalStrategy, JwtStrategy],
  controllers: [AuthController],
})
export class AuthModule {}
@Controller('auth')
export class AuthController {
  constructor(private readonly authService: AuthService) {}

  @UseGuards(LocalGuard)
  @Post('/login')
  async login(@Request() request) {
    return this.authService.login(request.user);
  }
}
@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly bcryptService: BcryptService,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(email: string, password: string): Promise<User> {
    try {
      const user = await this.userService.findByEmail(email);
      await this.bcryptService.comparePassword(password, user.password);
      return user;
    } catch (err) {
      throw new HttpException(err.message, HttpStatus.UNAUTHORIZED);
    }
  }

  async login(user: User) {
    const payload = { userEmail: user.email, userId: user.id };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}

In fact, I have to add the options object to the jwtService.sign() like this to make it work:

  async login(user: User) {
    const payload = { userEmail: user.email, userId: user.id };
    return {
      access_token: this.jwtService.sign(payload, {
        secret: process.env.JWT_SECRET,
      }),
    };

I'm searching for an explanation of "Why does the register method does not the work?", I expected to not have to add the option object in the sign() method.

Why?

And if the secret is not set, is the expiration set ?


Solution

  • The error thrown is due to process.env.JWT_SECRET being undefined and hence the secret in auth module. And the reason behind the env variable being undefined is due to the environment configuration setting in your application.

    To make this variable accessible in auth module, you should either dynamically import ConfigModule in auth module or define it globally like this:

    ConfigModule.forRoot({
      isGlobal: true,
    });
    

    Once the variable is accessible, you don't have to explicitly define it in the login method. And yes the expiration is set because it has nothing to do with environment variable configuration.