Ciprian Oancea
Ciprian Oancea

Reputation: 119

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.

Upvotes: 0

Views: 417

Answers (2)

Jay McDoniel
Jay McDoniel

Reputation: 70111

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')
  })
})

Upvotes: 2

Ayoub Touba
Ayoub Touba

Reputation: 2987

Be sure that you Call the ConfigService in your App Module constructor :

 export class AppModule {
  constructor(private configService: ConfigService) {}
}

Upvotes: 0

Related Questions