Management env variable with dotenv & TypeScript [JavaScript]


dotenv supports environment variable from .env file for Node.js project.

In this article, I would like to share initial configuration and some tip to use dotenv with TypeScript.

🐰 Installation

yarn add dotenv # npm install --save dotenv
yarn add @types/dotenv # npm install --dev-save @types/dotenv

🍄 Configuration

Add .env files in your project root, by the following command in terminal:

touch .env # for common configuration
touch .env.development # for dev configuration
touch .env.test # for test configuration

In .env files, you can write environment variables like this:

# Example
APP_ID=project_name
LOG_LEVEL=debug

After then, please add ./src/utils/config.ts to load the avobe files.

import * as dotenv from "dotenv";

dotenv.config();
let path;
switch (process.env.NODE_ENV) {
case "test":
path = `${__dirname}/../../.env.test`;
break;
case "production":
path = `${__dirname}/../../.env.production`;
break;
default:
path = `${__dirname}/../../.env.development`;
}
dotenv.config({ path: path });

export const APP_ID = process.env.APP_ID;
export const LOG_LEVEL = process.env.LOG_LEVEL;

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!