25

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?

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
Carven
  • 14,988
  • 29
  • 118
  • 161
  • Where (and when) are you reading in the `.env` file? – Kim Kern Apr 14 '19 at 08:50
  • @KimKern I'm reading the file in a module file which resides in the module's folder. The .env file is in the root of the project. I've updated my question to show when they are used. – Carven Apr 14 '19 at 09:00

7 Answers7

36

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) => ({
      secret: configService.jwtSecret,
    }),
    inject: [ConfigService],
}),

See this answer on how to create a ConfigService.

QcPerreault
  • 80
  • 1
  • 2
  • 7
Kim Kern
  • 54,283
  • 17
  • 197
  • 195
8

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.

hugo blanc
  • 310
  • 3
  • 14
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.

4

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

Kamuran Sönecek
  • 3,293
  • 2
  • 30
  • 57
  • @Kekson have you re-start app after set it? and please take care "ConfigModule is been loaded in the root module (e.g., AppModule)" – Kamuran Sönecek Aug 04 '20 at 12:33
  • 3
    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 Aug 04 '20 at 13:04
  • 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 – Kekson Aug 04 '20 at 13:20
  • @Kekson Other modules should be a child of your main module. If the other modules are not chield may you have define it again. – Kamuran Sönecek Aug 04 '20 at 13:31
4

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

import dotenv from "dotenv";

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

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

0

it is works for me

@Module({
    imports: [ConfigModule.forRoot({
        envFilePath: join(process.cwd(), 'env', `.env.${process.env.SCOPE.trim()}`),
    })]
})

The solution is to use the trim() function because in Windows spaces are added to the end of the value of the environment variable

JALF
  • 140
  • 1
  • 7
0

I had a similar issue. Had written the code on another machine in which it ran fine. Cloned the repo onto another machine tried to run but hit the the env variables issue because I didn't have the .env file. Copied it across but still got the error message. Removing node_modules and installing followed by nom run build solved the issue for me

Craig
  • 11
  • 1