0

I have created three env files : .env ,.env.test,.env.prod in my root directory.

.env file has

PORT=4000

DATABASE_URL="postgresql://postgres:1234@localhost:5432/postgres?schema=public"

JWT_SECRET="THIS_IS_A_SECRET_KEY_DEV_ENVIRONMENT"

JWT_EXPIRATION_TIME=3600

And my .env.test has

    PORT=4001
    
    DATABASE_URL="postgresql://postgres:1234@localhost:5432/postgres?schema=public"
    
    JWT_SECRET="THIS_IS_A_SECRET_KEY_TEST_ENVIRONMENT"
    
    JWT_EXPIRATION_TIME=2400

My app.moudle.ts looks like

const ENV = process.env.NODE_ENV;
console.log(ENV);
@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: !ENV ? '.env' : `.env.${ENV}`,
      load: [configuration],
      ignoreEnvFile: true,
    }),
  providers: [AppService],
  controllers: [AppController],
})
export class AppModule {
  constructor(private connection: Connection) {}
}

configuration.ts :

export default () => ({
    port: parseInt(process.env.PORT, 10) || 3000,
    jwt:{
        secret:process.env.JWT_SECRET,
        expiresIn:process.env.JWT_EXPIRATION_TIME
    }
  });

And my scripts are :

 "start:dev": "nest build && nest start --watch",
    "start:test": "NODE_ENV=test nest start --watch",

Controller code :

Logger.log(this.configService.get<string>('jwt.secret'));

When i inject conifgService in any controller and try log the jwt key it always fetches the key from .env file.Even when i run the app using script "start:test"

It always gets the value from .env file irrespective of script/environment Logs this for all the scripts "THIS_IS_A_SECRET_KEY_DEV_ENVIRONMENT"

Yashwanth Kata
  • 817
  • 8
  • 21

1 Answers1

1

I had the same problem. Check that you are not overwrite config with dotenv

import { config } from 'dotenv';
config();

If yes, you can pass to config options path with .env file.

config({path: '.env.development'});

or

 config({`.env.${process.env.NODE_ENV`})