Environment variables within Node.js



Resources
Configuration

Node.js applications benefit from being configured from Environment variables (here…) following one of the Twelve-Factor App (third law).

Configuration.ts file

export const corsMethods = process.env.CORS_METHODS;
export const corsUrl = process.env.CORS_URL;
export const database = { // MongoDB Atlas (https://www.mongodb.com/cloud/atlas)
    name: process.env.DB_NAME || 'New_York_City_Penitentiary_database',
    password: process.env.DB_PASSWORD || 'YouMayKnowMyPasswordFor$100.000...',
    user: process.env.DB_USER || 'FB'
};
console.assert(process.env.NODE_ENV === 'DEBUG' || process.env.NODE_ENV === 'RELEASE'); // 'DEBUG' or 'RELEASE' values expected...
export const port = process.env.PORT || 1963; // If 'PORT' env. variable is unset then exposes API at port '1963'...
// console.log(process.env); // Caution: sensitive data may be displayed...

.env file

# NODE_ENV = DEBUG
NODE_ENV = RELEASE

CORS_URL = *
CORS_METHODS = "GET, HEAD, PUT, PATCH, POST, DELETE"

DB_USER = FB
DB_PASSWORD = YouMayKnowMyPasswordFor$100.000...
DB_NAME = New_York_City_Penitentiary_database

PORT = 1963
Configuration by means of dotenv

dotenv loads data from .env file.

package.json file

"dependencies": {…, "dotenv": "^16.3.1", …},

Typescript

import dotenv from "dotenv"; // Install it in '"dependencies"'...
// Load data from '.env' file:
dotenv.config();
// console.log(JSON.stringify(process.env)); // Caution: sensitive data may be displayed...
Utilities ⤳ if-env, nodemon

dotenv can be preloaded by means of the -roption. To that extent, dotenv acts as a dev. dependency only

package.json file

"devDependencies": {…, "dotenv": "^16.3.1", …},
node -r dotenv/config.js dist/API.js

package.json file

"devDependencies": {…, "dotenv": "^16.3.1", …, "if-env": "^1.0.4", …},
"scripts": {
    …
    "server:NODE": "node -r dotenv/config dist/API.js",
    "server:NODEMON": "nodemon -r dotenv/config dist/API.js",
    "start": "if-env NODE_ENV=RELEASE && npm run start:RELEASE || npm run start:DEBUG",
    "start:DEBUG": "npm run build && npm run server:NODEMON",
    "start:RELEASE": "npm run build && npm run server:NODE",
    …
  },

nodemon aims at replacing the node command. Added value is the fact that the nodemon command automatically reloads JavaScript source files at changing time…

package.json file

"devDependencies": {…, "nodemon": "^2.0.22", …},
"scripts": {
    …
    "server:NODEMON": "nodemon -r dotenv/config dist/API.js",
    "start": "if-env NODE_ENV=RELEASE && npm run start:RELEASE || npm run start:DEBUG",
    "start:DEBUG": "npm run build && npm run server:NODEMON",
    …
  },