Search code examples
nestjs

NestJS - can't resolve ConfigService


I am using NestJS jwt passport to auth user. I follow the doc, here is my app module:

import { Module } from '@nestjs/common';
import { UserModule } from './user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthModule } from './auth/auth.module';
import { ConfigModule } from '@nestjs/config';
import configuration from '../config/configuration';

@Module({
  imports: [
      ConfigModule.forRoot({
          load: [configuration],
      }),
      TypeOrmModule.forRoot(),
      UserModule,
      AuthModule,
  ],
})
export class AppModule {}

And here is my auth module:

import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { PassportModule } from '@nestjs/passport';
import { UserModule } from '../user/user.module';
import { LocalStrategy } from './local.strategy';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './auth.controller';

@Module({
    imports: [
        UserModule,
        PassportModule,
        JwtModule.registerAsync({
            imports: [ConfigModule],
            useFactory: async (configService: ConfigService) => ({
                secret:  configService.get('jwt.secret'),
                signOptions: {
                    expiresIn: configService.get('jwt.expiresIn'),
                },
            }),
            inject: [ConfigService],
        }),
    ],
    providers: [AuthService, LocalStrategy, JwtStrategy],
    exports: [AuthService],
    controllers: [AuthController],
})
export class AuthModule {}

Every time I run npm run start, I got this error message:

Nest can't resolve dependencies of the JWT_MODULE_OPTIONS (?). Please make sure that the argument ConfigService at index [0] is available in the JwtModule context.

I have searched this problem, but still can't fix this. Someone can help me? Thanks.


Solution

  • One option, as mentioned by others, is to make the ConfigModule global with the isGlobal: true setting. Otherwise, in @nestjs/[email protected] it should be fixed and should now work as the docs show.