NestJs: Unable to read env variables in module files but able in service files?

13,952

Solution 1

Your .env file is not yet read in when your JwtModule is instantiated. So either read it in earlier e.g. in your main.ts before the nest app is created or better: create a ConfigService and make the dependency on your config explicit:

JwtModule.registerAsync({
    imports: [ConfigModule],
    useFactory: async (configService: ConfigService) => ({
      secretOrPrivateKey: configService.jwtSecret,
    }),
    inject: [ConfigService],
}),

See this answer on how to create a ConfigService.

Solution 2

You can use it as global for access from other modules.

When you want to use ConfigModule in other modules, you'll need to import it (as is standard with any Nest module). Alternatively, declare it as a global module by setting the options object's isGlobal property to true, as shown below. In that case, you will not need to import ConfigModule in other modules once it's been loaded in the root module (e.g., AppModule)

.https://docs.nestjs.com/techniques/configuration#use-module-globally

ConfigModule.forRoot({
  isGlobal: true
});

Also you can find here how to use config service: https://docs.nestjs.com/techniques/configuration#using-the-configservice

Solution 3

I just realize that I solve my problem also, just importing dotenv and calling the method config at the begining of my module (auth.module.ts).

import "dotenv" from dotenv;

dotenv.config({path:<path-to-env-file>})

Not need to specify the path if you are using the default .env file in the root of the project.

Solution 4

The declaring order is important in your use case.

This works:

@Module({
  imports: [
    ConfigModule.forRoot(),
    ScheduleModule.forRoot(),
    TypeOrmModule.forRoot({
      type: 'mongodb',
      host: process.env.SYN_MONGO_HOST,
      port: +process.env.SYN_MONGO_PORT,
      username: process.env.SYN_MONGO_USERNAME,
      password: process.env.SYN_MONGO_PASSWORD,
      database: process.env.SYN_MONGO_DATABASE,
      authSource: 'admin',
      autoLoadEntities: true,
    }),
  ],
  controllers: [],
  providers: [],
})
export class ConfigurationModule {}

When this doesn't

@Module({
  imports: [
    ScheduleModule.forRoot(),
    TypeOrmModule.forRoot({
      type: 'mongodb',
      host: process.env.SYN_MONGO_HOST,
      port: +process.env.SYN_MONGO_PORT,
      username: process.env.SYN_MONGO_USERNAME,
      password: process.env.SYN_MONGO_PASSWORD,
      database: process.env.SYN_MONGO_DATABASE,
      authSource: 'admin',
      autoLoadEntities: true,
    }),
    ConfigModule.forRoot(),
  ],
  controllers: [],
  providers: [],
})
export class ConfigurationModule {}

This is because ConfigModule is load before or after TypeOrmModule.

Solution 5

Like @KimKen said, the problem is that, by the time that the JwtModule is instantiated the environment variables still are not loaded. However, I have a different approach to @KimKen's answer that you might also be interested in.

First of all NestJS provide a ConfigModule that load the environment variables, so you don't need to create one, unless you wish handle it different than the usual. (https://docs.nestjs.com/techniques/configuration)

Now, to solve the problem I made the module (auth.module.ts) dynamic. In short words a dynamic module is module that receive parameters, and it depend on that input parameters for its right instantiation.(https://docs.nestjs.com/fundamentals/dynamic-modules)

The real thing going on here, is that the JwtModule is also a dynamic module because it depend on a variable for its right instantiation. So, that cause that also your module depend on parameters for its right instantiation, so make it dynamic! :).

Then your auth.module will be something like:

@Module({})
export class AuthModule {

    static forRoot(): DynamicModule {
        return {
            imports: [
                JwtModule.register({
                    secretOrPrivateKey: process.env.SECRET   // process.env.SECRET will return the proper value
                })
            ],
            module: AuthModule
        }
    }

Then it will be as easy as in your app.module or where ever you load the auth.module import it through the forRoot static method.

import { ConfigModule } from '@nestjs/config';

@Module({
    imports: [ConfigModule.forRoot(), AuthModule.forRoot()]
})

Note: I recommend import ConfigModule once in the app.module.ts

PD: You could make the dynamic auth.module receive a parameter in the forRoot method and in the app.module pass the environment variable process.env.SECRET

AuthModule.forRoot(process.env.SECRET)

but it seems that dynamic modules are loaded last so there is not need for that.

Share:
13,952
Carven
Author by

Carven

Updated on June 21, 2022

Comments

  • Carven
    Carven almost 2 years

    I have an .env file at the root of my NestJs project with some env variables in it.

    The strange thing is that I am able to read the variables in service files but not in module files.

    So in a service file like users.service.ts, this works:

    saveAvatar() {
        const path = process.env.AVATAR_PATH    // returns value from .env
    }
    

    However, when accessing a path in a module file like auth.module.ts, this returns an empty value:

    @Module({
        imports: [
           JwtModule.register({
              secretOrPrivateKey: process.env.SECRET   // process.env.SECRET returns an empty string
           })
        ]
    })
    

    Why is that so? How can I reliably access environmental variables in the .env file in NestJs?

  • Kamuran Sönecek
    Kamuran Sönecek almost 4 years
    @Kekson have you re-start app after set it? and please take care "ConfigModule is been loaded in the root module (e.g., AppModule)"
  • Kekson
    Kekson almost 4 years
    yes but restart did not help, in my app.module.ts i have set this ConfigModule.forRoot({ isGlobal: true }) and in other modules i have process.env.PORT but it still does not read from env
  • Kekson
    Kekson almost 4 years
    If i put ConfigModule.forRoot() in other modules imports as well as in AppModule (as isGlobal: true) than it works fine... seems weird but it works
  • Kamuran Sönecek
    Kamuran Sönecek almost 4 years
    @Kekson Other modules should be a child of your main module. If the other modules are not chield may you have define it again.