Search code examples
environment-variablesnestjsnestjs-config

unable to load different .env files according to git branches, NestJs v10


I'm trying to set different .env files for my dev and prod environment accoridng to my git branches, like I want to set .env.dev for dev branch and .env.prod for main branch, So whenever I switch between branches I don't have to manually comment or uncomment envFilePath in ConfigModule.

But the issue is that the process.env isn't working. As i'm not able to connect with my database and face error Unable to connect to database

Code

import simpleGit from 'simple-git';


@Module({
  imports: [
    setConfigModule(),
    MongooseModule.forRoot(
      `mongodb://${process.env.HOST}:${process.env.PORT}/${process.env.NAME}?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false`,
    ),

  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

async function setConfigModule() {
  const git = simpleGit();
  const gitBranches = await git.branch();
  const currentBranch: string = gitBranches.current;
  console.log(currentBranch);

  if (currentBranch === 'main') {
    return ConfigFactory.loadProdConfig();
  }

  return ConfigFactory.loadDevConfig();
}

export class ConfigFactory {
  static loadDevConfig() {
    return ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: '.env.dev',
    });
  }

  static loadProdConfig() {
    return ConfigModule.forRoot({
      isGlobal: true,
      envFilePath: '.env.prod',
    });
  }
}

When I do this It works fine

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true, envFilePath: '.env.dev' }),
    MongooseModule.forRoot(
      `mongodb://${process.env.HOST}:${process.env.PORT}/${process.env.NAME}?readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false`,
    ),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Solution

  • Rather than reading from process.env you should be using ConfigService from @nestjs/config via the forRootAsync method on MongooseModule