To use .env variables in main app module file for database connection with Node Nest.js, we can use the dotenv package.
To install it, we run
npm install dotenv
Then we add the scripts with
{
"scripts": {
//...
"start:local": "NODE_ENV=local npm run start",
"start:dev": "NODE_ENV=dev npm run start"
}
}
to set the NODE_ENV environment variable before starting the app.
Then we load the .env file for the environment with
require("dotenv").config({ path: `../${process.env.NODE_ENV}.env` });
We get the NODE_ENV environment variable with process.env.NODE_ENV.
And we call config to load the .env file at the path.