Search code examples
javascriptnode.jstypescriptnestjsdotenv

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


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?


Solution

  • 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.