Categories
JavaScript Answers

How to use .env variables in main app module file for database connection with Node Nest.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.