Solved: require(‘dotenv’).config()

An understanding of environment variables is fundamental when developing applications with Node.js. One might wonder, what exactly are these environment variables? They are quite simply dynamic-named values on your machine that can be employed to hoard data that needs to be used by your applications. To manage these when working with Node.js, we employ a third party package dotenv that’s used to load variables from a .env file into process.env.

Setting Up Dotenv

The first step in employing dotenv in your Typescript application is installing the package itself. This can be accomplished by running the following command in your project root:

npm install dotenv

Upon completion of the dotenv package installation, the next move is to make a .env file at the root of your Typescript application. This file is then mostly used to store sensitive information such as your API keys, database passwords, or configuration settings that you wouldn’t want a potential hacker to see.

How to Use Dotenv

After creating the .env file, we need to call dotenv’s config method to set up our environment variables. Require `dotenv` and call `config()` method at the top of your entry file.


require('dotenv').config()

What’s important to note here is that the order of the invocation of code is relevant because once `dotenv.config()` is invoked, environment variables will be accessible via `process.env`.

The .env file from where dotenv package fetches data usually has KEY=VALUE pairs. It is feasible to use these keys in your Typescript code by invoking `process.env.KEY`.

Understanding Environment Variables

On the other hand, we might have different values for variables for different environments. We can have one value for the ‘development’ environment and a different value for the ‘production’ environment. To cater to this problem, we can add a switch condition that uses different environment variables based on the ‘NODE_ENV’ value.


id let config = {}

switch (process.env.NODE_ENV) {
  case 'development':
    config = process.env.DEVELOPMENT
    break
  case 'production':
    config = process.env.PRODUCTION
    break
}

This allows us to easily scale and maintain consistency in different environments.

In the realm of Node.js development, understanding and properly implementing environment variables is a vital stage for any professional. Leveraging required packages like `dotenv` not only increase our efficiency as developers, but also promotes secure, scalable and maintainable code. The understanding of `dotenv` will set you apart and make you a better Node.js developer.

Related posts:

Leave a Comment