NestJs not reading environmental variables

Viewed 1563

I followed the the Nest documentation to create the config but it's not working

app.module.ts

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    TypeOrmModule.forRoot(config),
    AuthModule,
    UsersModule,
    MailModule,
    CloudinaryModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})

.env file is on the src folder

mail.module.ts

@Module({
  imports: [
    MailerModule.forRoot({
      transport: {
        service: 'Gmail',
        auth: {
          user: process.env.MAIL_USER,
          pass: process.env.MAIL_PASS,
        },
      },
    }),
  ],

But when I run the app its undefined my key value pairs are also there.

1 Answers

The problem is ConfigModule's env variables are only available at run time but not on the nestjs initial state.

To allow getting the .env after nestjs initialised, you can use async config to in MailerModule.

mail.config.ts

export class MailerConfig implements MailerOptionsFactory {
  createMailerOptions(): MailerOptions | Promise<MailerOptions> {
    console.log(process.env.MAIL_USER); // should have value
    return {
      transport: {
        service: 'Gmail',
        auth: {
          user: process.env.MAIL_USER,
          pass: process.env.MAIL_PASS,
        },
      },
    };
  }
}

mail.module.ts

console.log(process.env.MAIL_USER); // undefined
@Module({
  imports: [
    MailerModule.forRootAsync({
      useClass: MailerConfig,
    }),
  ],
})
export class MailModule {}

you can use useFactory as well without the need of class, here I want to console.log the .env for you to check with so i used config class.

Related