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
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"
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,
}),
This tells NestJS to dynamically load the correct environment file based on NODE_ENV.
Step 5: Run Your Application
Now you can run your app in different environments easily:
npm run start:test
npm run start:local
Or any other environment you define:
npm run start:other
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:
- LinkedIn: https://linkedin.com/in/dawit-girma-7b8867228/
- Email: realdavis7779@gmail.com
- GitHub: https://github.com/dedawit
Top comments (0)