Search code examples
nestjsdotenv

Dotenv variable is undefined


I have one module (auth module) where I register JwtModule:

JwtModule.register({
      secret: process.env.SECRET_KEY,
      signOptions: { expiresIn: '60m' },
    }),

Register function looks like this: static register(options: JwtModuleOptions): DynamicModule;

JwtModule is defined in node_modules (jwt.module.js)

let JwtModule = JwtModule_1 = class JwtModule {
    static register(options) {
        console.log(options);
        console.log(process.env.SECRET_KEY);
        return {
            module: JwtModule_1,
            providers: jwt_providers_1.createJwtProvider(options)
        };
    }

In app.module.ts I have

ConfigModule.forRoot({
      isGlobal: true,
    }),

process.env.SECRET_KEY is undefined in node_modules file (console.log(process.env.SECRET_KEY)), but signOptions: { expiresIn: '60m' } is defined.

If I try to write to console SECRET_KEY from .env everywhere else is defined, but in node_modules is undefined.


Solution

  • The ConfigModule's ConfigService runs dotenv's config() method, but all decorators run at the same time, so the config() method is not called yet. You can use the async registration instead and use the ConfigService like so

    JwtModule.registerAsync({
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        secret: config.get('SECRET_KEY')
      })
    })