How to manage different config environments in nestjs

Assuming you have the following config files in the root of the project: env.development, env.staging, env.test

Here is how I would implement it:

In the app.module.ts file:

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

const ENV = process.env.NODE_ENV;

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: !ENV ? '.env' : `.env.${ENV}`,
    }),
  ],
  controllers: [AppController],
})
export class AppModule {}

Inspired by this solution: https://github.com/nestjsx/nestjs-config#using-different-env-files


You can use the config library as mentioned in the official documentation. Otherwise you can use the npm library dotenv.

In either way what really matters is how you organise your .env files. Env files are supposed to contain database credentials, encryption secret and many confidential data, so its not really a good idea to put them in version control. Instead you should store the .env file in the system. Production server will have .env file with production secrets, developer server can have .env file with local secrets. Flag .env to be ignored by git. In this way you won't have to change according to environment, it will automatically take the right configuration based on which server you are deploying.