Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the configurations from within a module import in NestJS?

Let's say I have my module defined as below:

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
    JwtModule.register({
      // Use ConfigService here
      secretOrPrivateKey: 'secretKey',
      signOptions: {
        expiresIn: 3600,
      },
    }),
    PrismaModule,
  ],
  providers: [AuthResolver, AuthService, JwtStrategy],
})
export class AuthModule {}

Now how can I get the secretKey from the ConfigService in here?

like image 967
THpubs Avatar asked Aug 31 '25 23:08

THpubs


1 Answers

You have to use registerAsync, so you can inject your ConfigService. With it, you can import modules, inject providers and then use those providers in a factory function that returns the configuration object:

JwtModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    secretOrPrivateKey: configService.getString('SECRET_KEY'),
    signOptions: {
        expiresIn: 3600,
    },
  }),
  inject: [ConfigService],
}),

For more information, see the async options docs.

like image 73
Kim Kern Avatar answered Sep 03 '25 13:09

Kim Kern