'nestjs process.env.variable is undefined in my auth.module.ts

im trying to test jwt auth in nestjs.

when i called jwtService.sign(); it shows error secretOrPrivateKey must have a value - {} secret is undefined.

but in AuthController, porcess.env.JWT_SECRET_KEY is work.

i dont know why it is not work.

how can i fix it ?

auth.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      load: [AppConfig, MySqlConfig, OracleConfig],
      envFilePath: `${process.env.NODE_ENV}` == '' ? '.env.dev' : `.env.${process.env.NODE_ENV}`,
      validationSchema: Joi.object({
        NODE_ENV: Joi.string()
          .valid('dev', 'stg', 'prd'),
      }),
    }),
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService, Logger],
})
export class AppModule {}

app.module.ts

@Module({
  imports: [
    PassportModule,
    JwtModule.register({
       secret: process.env.JWT_SECRET_KEY,
      signOptions: { expiresIn: '1d' },
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy, LocalStrategy],
  exports: [AuthService],
})
export class AuthModule {}

main.ts

async function bootstrap() {
  const app = await NestFactory.create(AppModule, {
    bufferLogs: true,
  });
  app.enableShutdownHooks();
  app.useLogger(app.get(MyLogger));

  const configService = app.get(ConfigService);
  const logger = app.get(MyLogger);
  const config = new DocumentBuilder()
    .setTitle('nestjs-tst-boilerplate')
    .setDescription('The nestjs-tst-boilerplate API description')
    .setVersion('0.0.1')
    .addTag('tag')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  await app.listen(configService.get<number>('app.port'));
  logger.log(`Application running on [${configService.get<string>('app.env')}] enviroment. ${await app.getUrl()}`);
}
bootstrap();


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source