Environment

Node.js Environment

Environment variable

Install Packages

npm install dotenv --save
yarn add dotenv

Create a .env file

APP_ENV=dev
PORT=5566

Get the env variable

Normal import

// server.js
require('dotenv').config()
console.log(process.env);
console.log(process.env.APP_ENV);
console.log(process.env.PORT);

ES6 import

// server.js
import * as dotenv from 'dotenv' // see https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import
dotenv.config();
console.log(process.env);
console.log(process.env.APP_ENV);
console.log(process.env.PORT);

Test to get the environment variable

node server.js

Pass environment variable via CLI command

APP_ENV=production PORT=7788 node server.js
// server.js
require('dotenv').config()
console.log(process.env);
console.log(process.env.APP_ENV); // production
console.log(process.env.PORT);    // 7788

Environment variable priority

If you use the .env file and pass the environment variable via CLI command at the same time, then the dotenv will use the CIL environment variable first.

  1. CLI environemnt variable
  2. .env file environemnt variable

Reference

Packages