Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use JwtService in nestjs middlware?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading