Home > Software design >  How to use JwtService in nestjs middlware?
How to use JwtService in nestjs middlware?

Time:11-02

I have registered JwtModule in my UserModule as:

@Module({
  imports: [
    // MongooseModule.forFeature([{ name: User.name, schema: userSchema }]),
    
    JwtModule.register({
      secret: process.env.JWT_TOKEN,
      signOptions: { expiresIn: '60s' },
    }),
  ],
  controllers: [UserController],
  providers: [UserService, UserRepository],
  exports: [UserService, UserRepository],
})

And I have registered middleware in my UserModule as:

export class UserModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(CurrentAuth).forRoutes({
      path: '*',
      method: RequestMethod.GET,
    });
  }
}

In my CurrentAuth middleware I have initialized JwtService as:

export class CurrentAuth implements NestMiddleware {
  constructor(private tokenService: JwtService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const payload = this.tokenService.verify("mytoken");

    next();
  }
}

But it gives me error:

TypeError: Cannot read properties of undefined (reading 'verify')

Please help me with my code or just suggest something if you know things.

CodePudding user response:

Looks like you're missing the @Injectable() on the CurrentAuth class. That's required so that Typescript emits the metadata of the parameters of the constructor. Make sure you also add the middleware to the providers array

  • Related