CodexBloom - Programming Q&A Platform

How to implement guide with environment-specific configuration loading in node.js with dotenv

πŸ‘€ Views: 0 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-15
node.js dotenv configuration JavaScript

I'm experimenting with I'm stuck trying to I've looked through the documentation and I'm still confused about I'm experiencing an scenario with loading environment-specific configurations in my Node.js application using the `dotenv` package. I have a `.env` file for development and another file named `.env.production` for production configurations. However, when I run my application in production mode, it still seems to be loading the variables from the `.env` file instead of the `.env.production` file. Here’s how I am trying to load the configurations: ```javascript const dotenv = require('dotenv'); const path = require('path'); const envFile = process.env.NODE_ENV === 'production' ? '.env.production' : '.env'; dotenv.config({ path: path.resolve(__dirname, envFile) }); ``` I've set `NODE_ENV` to `'production'` in my environment before starting the app, but I still see the variables from the development file showing up in my console logs: ```javascript console.log(process.env.DB_HOST); // This prints the development DB_HOST instead of production ``` I’ve verified that the `.env.production` file exists in the correct path and is readable. I also tried to log the value of `envFile` before calling `dotenv.config()` to ensure it's resolving correctly, and it logs `.env.production` as expected. Is there something I'm missing in the configuration or how dotenv loads the files? Also, does the order of loading these configurations matter if I have other configuration files? Any insights would be greatly appreciated! Thanks! My development environment is Windows. Thanks in advance! My development environment is Linux. I'd really appreciate any guidance on this.