user842225
user842225

Reputation: 5999

Nest can't resolve dependencies of the JwtService though exported from another module

I am using @nestjs/jwt in my NestJS project.

I have two modules, AuthModule and AppModule.

AuthService:

import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { ForbiddenException } from '@nestjs/common';

@Injectable()
export class AuthService {
  constructor(private readonly jwt: JwtService) {}

  async validate(token: string) {
    return this.jwt.verify(token);
  }
   ...
}

AuthModule:

import { Module } from '@nestjs/common'
import { TokenService } from './auth.service'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { JwtModule } from '@nestjs/jwt'

@Module({
  imports: [
    JwtModule.register({
          secret: "mysecret",
          signOptions: { expiresIn: "60s" },
        }),
  ],
  // I provide AuthService & JwtService
  providers: [AuthService, JwtService], 
  // I export AuthService and JwtService
  exports: [AuthService, JwtService],
})
export class AuthModule {}

AppModule:

@Module({
  imports: [
    AuthModule,
    ...
  ],
  controllers: [AppController],
  // I provide AuthService & JwtService also in AppModule
  providers: [AppService, JwtService],
})
export class AppModule {}

(The AppController invokes AuthService instance to validate token.)

I constantly get error:

Nest can't resolve dependencies of the JwtService (?). Please make sure that the argument JWT_MODULE_OPTIONS at index [0]

Why is that? Where do I miss?

Upvotes: 4

Views: 4513

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70302

You don't need to add JwtService to the providers. Nest will look through the current module's providers, then the imported module's exports, and then the global module's exports to find providers that are not immediately in the level it's resolving the providers in. This means that for AuthService it'll look up to the JwtModule's exports and find the JwtService already created, and use that instance. Then in the AppModule you don't need to mention the AuthService or JwtService, just import the AuthModule that exports the AuthService and JwtModule (doing some module re-exporting) and you should be good to go


EDIT: Added module code:

AuthModule

import { Module } from '@nestjs/common'
import { TokenService } from './auth.service'
import { ConfigModule, ConfigService } from '@nestjs/config'
import { JwtModule } from '@nestjs/jwt'

@Module({
  imports: [
    JwtModule.register({
          secret: "mysecret",
          signOptions: { expiresIn: "60s" },
        }),
  ],
  providers: [AuthService],
  exports: [AuthService, JwtModule],
})
export class AuthModule {}

AppModule

@Module({
  imports: [
    AuthModule,
    ...
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Upvotes: 4

Related Questions