typescriptnestjsnestjs-jwt

NestJS JwtService throws Error: secretOrPrivateKey must have a value (not due to env variables)


I need to use jwt in my project, so decided to go with: "@nestjs/jwt": "^10.2.0"

In my shared module I am configuring the secret keys and have also ensured that the values are defined by logging them. Image showing shared module and terminal and how secret is loaded from env variables

Below is the code for my user.service.ts where I am using my jwtService to sign the mobileNumber. Removed all mobileNumber verification steps for now just trying to debug jwtService.

enter image description here

I noticed that if I pass secret key to the sign function myself in jwt options, then it works fine. But then what was the use of configuring it in shared module where I passed the secret key and expired in time.

Also reading another answers on the internet I found that it is probably due to me adding JwtService in the providers array which probably creates a new instance of the JwtService, importing jwt service as provider in app.module.ts

but if I don't do that I get this error:

Error: Nest can't resolve dependencies of the UserService (UserRepository, ?). Please make sure that the argument JwtService at index [1] is available in the UserModule context.

Potential solutions:
- Is UserModule a valid NestJS module?
- If JwtService is a provider, is it part of the current UserModule?
- If JwtService is exported from a separate @Module, is that module imported within UserModule?
  @Module({
    imports: [ /* the Module containing JwtService */ ]
  })
async register(createUserDto: CreateUserDto) {
    const { mobileNumber } = createUserDto;
    return this.jwtService.sign(mobileNumber, {
      secret: 'testkajfkdf',
    });
  }

Please helppp


Solution

  • Remove the JwtService from the providers array of the UserModule, add the JwtModule to the exports of the SharedModule, and add the SharedModule to the imports of the UserModule