Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage different config environments in nestjs

Tags:

nestjs

I'd like to have a few environments, let's say development, production, test. These environments should be independent and use their own set of config parameters, e.g. for DB, SERVER_PORT, USER etc. They should not be in the code base, so I think they should be different .env files. That's to say, I should be able to load different .env files depending on what environment is active. Also, it's not clear where I have to set that env switcher.

Maybe it should be a single .env file that has the NODE_ENV parameter, that param can be set to any of the above-mentioned values, be that development, production or test. And depending on the value of this parameter a necessary set of config parameters gets automatically loaded.

I've read the documentation, it seems a little confusing to me at the moment.

Seems like there should be some config factory.

like image 740
Albert Avatar asked Apr 25 '20 19:04

Albert


People also ask

How do I see environment variables in NestJS?

You can now use process.env file in your project, you'll now have access to your environment variables by using process. env anywhere in your NestJS app. import { NestFactory } from '@nestjs/core'; import { AppModule } from './app. module'; async function bootstrap() { const app = await NestFactory.

What is env config?

GitHub - sitture/env-config: A simple utility to manage environment configs in Java-based projects by merging . properties files and environment variables overrides.

How is process env set?

The process. env global variable is injected by the Node at runtime for your application to use and it represents the state of the system environment your application is in when it starts. For example, if the system has a PATH variable set, this will be made accessible to you through process.


1 Answers

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

like image 64
kessir Avatar answered Oct 03 '22 18:10

kessir