DEV Community

Cover image for One Codebase, Multiple Environments: Mastering Env Config in NestJS
Dawit Girma
Dawit Girma

Posted on

One Codebase, Multiple Environments: Mastering Env Config in NestJS

Have you ever wondered:

“Can I tell NestJS which environment variables to load when running my app?”

The simple answer is: yes, you absolutely can.

This is not one of my major deep-dive articles, but I wanted to share it because it used to be a real headache for me—and it might be for you as well.

At our company, we constantly switch between local, development, and production databases. What we used to do was far from ideal:

  • Comment one .env file
  • Uncomment another
  • Repeat the same process again and again

It worked, but it was messy, error-prone, and frustrating.
Until I found a cleaner and more scalable approach.

Step 1: Install Required Packages

We need two packages:

  • @nestjs/config for loading environment variables
  • cross-env for handling NODE_ENV across platforms
npm install @nestjs/config cross-env
Enter fullscreen mode Exit fullscreen mode

Step 2: Create Multiple .env Files

Create environment-specific files such as:

  • .env.local
  • .env.test
  • .env.production

You can create as many as needed depending on your workflow.

Step 3: Define Scripts in package.json

"start:test": "cross-env NODE_ENV=test nest start --watch",
"start:local": "cross-env NODE_ENV=local nest start --watch"

Enter fullscreen mode Exit fullscreen mode

The key idea:

The value of NODE_ENV must match the suffix of your .env file.
For example:
NODE_ENV=test loads .env.test
NODE_ENV=local loads .env.local

Step 4: Configure NestJS

In your app.module.ts, add:

ConfigModule.forRoot({
 envFilePath: `.env.${process.env.NODE_ENV}`,
 isGlobal: true,
}),
Enter fullscreen mode Exit fullscreen mode

This tells NestJS to dynamically load the correct environment file based on NODE_ENV.

Step 5: Run Your Application
Enter fullscreen mode Exit fullscreen mode

Now you can run your app in different environments easily:

npm run start:test 
npm run start:local
Enter fullscreen mode Exit fullscreen mode

Or any other environment you define:

npm run start:other
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

What used to be a repetitive and error-prone process is now clean and predictable.

No more commenting and uncommenting configuration files.

No more accidental connections to the wrong database.

Just one codebase running across multiple environments in a controlled way.

Contact

If you have any questions, feel free to reach out:

Top comments (0)