Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

env-var-helpers

andfaulkner393MIT5.2.0TypeScript support: included

Grab quick info from common environment variables (NODE_ENV, LOG_LEVEL, etc.). Convenience methods.

environment, environment-variables, config, variables, configuration, configuration-management, project-config, project-configuration, configuration, environment-config, env-config, env-configuration, environment-configuration, NODE_ENV, LOG_LEVEL, QA, UAT, deployment, orchestration, release, helpers, utils

readme

env-var-helpers

Environment variable helper functions & pre-resolved values

  • Extracts & resolves (to type) commonly used values from process.env without fuss

Helpers to get info from:

  • NODE_ENV
  • LOG_LEVEL
  • RELEASE_ENV
  • LOADED_MOCHA_OPTS (defined by default by Mocha)
  • TEST_MODE
  • AVOID_WEB
  • TEST_SECURITY / SECURITY_TEST
  • IE_COMPAT
  • IS_LOCAL
  • SKIP_BASIC_AUTH

Converts boolean strings to boolean: e.g. true, "true", and "TRUE" all become true

Case-insensitive environment variable value detections

  • NODE_ENV=development, Development, & DEVELOPMENT all resolve to 'development'

Isomorphic: usable with Typescript, Node, Babel, Webpack, & browser JS (ES5 and up)

Basic examples

Script run with NODE_ENV=prod & LOG_LEVEL is not set:

import {
    isDevelopment,
    isQA,
    isVerbose,
    nodeEnv,
    logLevel,
    isLocal,
    skipBasicAuth
} from 'env-var-helpers';

if (isDevelopment) {
    // Initialize mobx-react-devtools if NODE_ENV=dev, development, or not set
}

if (isQA) {
    // Inject QA tools if RELEASE_ENV=qa
}

if (isVerbose) {
    console.log(`Log this only if LOG_LEVEL=verbose`);
}

if (isLocal) {
    // Download latest JSON from remote API for local reference if IS_LOCAL=true
}

if (!skipBasicAuth) {
    // Activate basic auth if SKIP_BASIC_AUTH=true or NODE_ENV=production
}

console.log(nodeEnv);  // => 'production'
console.log(logLevel); // => 'info' (shows default since it's not set)

API

All values are static boolean constants (true | false), unless otherwise specified.

isDevelopment, isDev

Env var: NODE_ENV (process.env.NODE_ENV) Default: true

True if NODE_ENV=dev or NODE_ENV=development

Example:

import {isDev, isDevelopment} from 'env-var-helpers';

if (isDev) console.log("run if NODE_ENV is 'development'");
if (isDevelopment) console.log("run if NODE_ENV is 'development'");

isProduction, isProd (NODE_ENV)

Env var: NODE_ENV Default: false

True if NODE_ENV=prod or NODE_ENV=production

Example:

import {isProd, isProduction} from 'env-var-helpers';

if (isProd) console.log("run if NODE_ENV is 'production'");
if (isProduction) console.log("run if NODE_ENV is 'production'");

isTrace, isSilly, isVerbose, isDebug, isInfo, isWarn, isError, isWTF / isWtf

Env var: LOG_LEVEL Default: true for isInfo & up, false for isDebug & below

True if LOG_LEVEL is set to the namesake log level or one that is more verbose

Example:

import {isVerbose, isWTF} from 'env-var-helpers';

if (isVerbose) {
    console.log('Display this if LOG_LEVEL is "trace", "silly", or "verbose"');
}

if (isWTF) {
    console.log("Log if LOG_LEVEL is wtf, error, warn, info, debug, verbose, silly, or trace");
}

isReleaseEnvDev, isReleaseEnvProd, isReleaseEnvQA / isQA, isReleaseEnvUAT / isUAT

Env var: RELEASE_ENV Type: string Default: true for isReleaseEnvDev, false for all others

True if RELEASE_ENV is set to the namesake environment type.

Example: if we run the following script with RELEASE_ENV=qa node some-script.js:

import {isQA, isReleaseEnvQA} from 'env-var-helpers';
import {isUAT, isReleaseEnvUAT, isReleaseEnvDev, isReleaseEnvProd} from 'env-var-helpers';

// Below both output "Runs if process.env.RELEASE_ENV=qa"
if (isReleaseEnvQA) console.log('Runs if process.env.RELEASE_ENV=qa');
if (isQA)           console.log('Runs if process.env.RELEASE_ENV=qa');

// The following don't run, because the RELEASE_ENV doesn't match
if (isReleaseEnvDev)  console.log('Runs if process.env.RELEASE_ENV=dev or development');
if (isReleaseEnvProd) console.log('Runs if process.env.RELEASE_ENV=prod or production');
if (isReleaseEnvUAT)  console.log('Runs if process.env.RELEASE_ENV=uat');
if (isUAT)            console.log('Runs if process.env.RELEASE_ENV=uat');

releaseEnvShort (RELEASE_ENV)

Env var: RELEASE_ENV Type: string Default: 'dev', or short-form of NODE_ENV value if set

Current release environment value, in 2-4 letter form.

Mapping:

  • development -> dev
  • qa -> qa
  • uat -> uat
  • production -> prod

For use when determing which APIs to make requests to based on current release environment

  • e.g. in "QA", POST to 'qa.example.ca/api/login'; In "dev", POST to 'dev.example.ca/api/login'

Example

Run with RELEASE_ENV=qa node some-script.js:

import {releaseEnvShort}

const loginRequestRoute = `https://www.${releaseEnvShort}.example.com/api/login`;

console.log(loginRequestRoute); // => "https://www.qa.example.com/api/login"

isTestMode

Env var: TEST_MODE Default: false

Is true if process.env.TEST_MODE is set to true (TEST_MODE=true)

  • e.g. script was run with: TEST_MODE=true node some-script.js

isIeCompat / isIECompat

Env var: IE_COMPAT Default: false

Is true if process.env.IE_COMPAT is set to true.

  • e.g. script was run with: IE_COMPAT=true node some-script.js

isProdOrSecurityTest / prodOrSecurityTest

Env vars: TEST_SECURITY & SECURITY_TEST Default: false

Is true if NODE_ENV=production, TEST_SECURITY=true, or SECURITY_TEST=true e.g. script was run with either:

*   `SECURITY_TEST=true node some-script.js`
*   `NODE_ENV=production node some-script.js`

isAvoidWeb, avoidWeb

Env var: AVOID_WEB Default: false

Is true if AVOID_WEB=true.

Purpose: environment variable requesting total avoidance of internet usage in a build.

  • e.g. no CDNs (usage of local bundles instead)

isMocha, isMochaEnv, runByMocha

Env vars: LOADED_MOCHA_OPTS & mocha

Is true if process.env.mocha or process.env.LOADED_MOCHA_OPTS is 'true'.

Should always be true if Mocha ran the current script, and never true otherwise.

  • Mocha sets this value automatically when it is launched.

isLocal

Env var: IS_LOCAL Default: false

Is true if IS_LOCAL is true.

Purpose: set to true if running in local environment (i.e. on localhost).

skipBasicAuth, isSkipBasicAuth, doSkipBasicAuth

Env var: SKIP_BASIC_AUTH Default: false

Is true if SKIP_BASIC_AUTH environment variable is true.

Purpose: set to true for turning basic auth off. Use to make basic auth handling conditional, based on route and/or deployment environment, etc.

nodeEnv

Env var: NODE_ENV Type: string Default: 'development'

Directly returns the NODE_ENV value. Automatically resolves it long-form e.g. 'dev' becomes 'development'.

logLevel

Env var: LOG_LEVEL Type: string Default: 'info'

Directly returns the LOG_LEVEL value.


Environment variables handled

NODE_ENV

Standard NODE_ENV values, as used by Express and React

Values:

  • development (DEFAULT)
  • production

LOG_LEVEL

Values:

  • trace
  • silly
  • verbose
  • debug
  • info
  • warn
  • error
  • wtf

RELEASE_ENV

Generally used to "mark" different deployment targets: e.g. www.dev.example.com, www.qa.example.com

Values:

  • dev / development
  • prod / production
  • qa
  • uat

TEST_MODE

If unit tests are currently being run, set this to true

Values:

  • true
  • false (DEFAULT)

SECURITY_TEST / TEST_SECURITY

Flag to turn security features on/off in dev without switching to full prod mode For use e.g. when working with TLS, authentication, CSRF blockers, etc.

Values:

  • true
  • false (DEFAULT)

IE_COMPAT

Turn on to compile app to run in Internet Explorer. Automatically set to true (if env-var-helpers imported), if NODE_ENV=production.

Values:

  • true
  • false (DEFAULT)

mocha / LOADED_MOCHA_OPTS

LOADED_MOCHA_OPTS automatically set to true if code was run by Mocha. process.env.mocha is an alternative if you want to manually declare that code is run by Mocha

  • In this case, declare process.env.mocha = true at the top of your test files

Values:

  • true
  • false (DEFAULT)

IS_LOCAL

Turn on if running in localhost - i.e. if special behaviours are needed locally

Values:

  • true
  • false (DEFAULT)

SKIP_BASIC_AUTH

Set to true to shut basic auth off on certain routes

Values:

  • true
  • false (DEFAULT)

changelog

5.2.0

Export directly resolved values of string variables:

  • nodeEnv (for NODE_ENV)
  • logLevel (for LOG_LEVEL)

Improve boolean environment variable resolution:

  • Handling of 'f' & 't' values
    • e.g. for IS_LOCAL=t, isLocal resolves to true
  • Fixed edge cases where detection was not case-insensitive

env namespace consistently contains resolved values

  • Previously, some properties held the raw values

Fix edge cases for string matching

Major revamp of README

Upgrade mad-logs & prettier

5.1.0

Remove package lock (package-lock.json)

Fix typings in outputted values (no more 'any' values)

Add IDE-friendly docs to all exports

Add handling for SKIP_BASIC_AUTH environment variable, with exports:

  • skipBasicAuth
  • isSkipBasicAuth
  • doSkipBasicAuth

5.0.1

Switch transpile target to ES5

Remove mad-logs dependency (make devDependency instead)

4.1.0

Add isLocal helper, for handling IS_LOCAL environment variable

4.0.1

README brought up to date

4.0.0

Remove most releaseEnvShort aliases:

  • releaseEnvAbbreviation
  • releaseEnvironmentShort
  • releaseEnvironmentAbbrev
  • releaseEnvironmentAbbreviation

Remove all combined Mocha + LOG_LEVEL environment variable status aliases:

  • isVerboseMocha, isVerboseTest, isMochaVerbose, isTestVerbose
  • isVTest, isVMocha, isMochaV, isTestV
  • isDebugMocha, isDebugTest, isMochaDebug, isTestDebug
  • isSillyMocha, isSillyTest, isMochaSilly, isTestSilly

Remove all isMocha (i.e. "Was this code run by Mocha?") aliases except isMochaEnv & runByMocha:

  • runViaMocha
  • runThruMocha
  • wasRunByMocha
  • wasRunViaMocha
  • wasRunThruMocha
  • loadedMochaOpts

Remove isAvoidWeb alias: "doAvoidWeb"

Remove isIECompat aliases:

  • isIECompatMode
  • isIeCompatMode

Remove isReleaseEnvUAT aliases:

  • isUat
  • isReleaseEnvUat

Remove isReleaseEnvQA aliases:

  • isQa
  • isReleaseEnvQa

Remove LOG_LEVEL env var helper aliases:

  • isLogSilly
  • isLogVerbose
  • isLogDebug
  • isLogInfo
  • isLogWarn
  • isLogError
  • isLogWTF
  • isLogWtf
  • logGtEqlSilly
  • logGtEqlVerbose
  • logGtEqlDebug
  • logGtEqlInfo
  • logGtEqlWarn
  • logGtEqlError
  • logGtEqlWTF
  • logGtEqlWtf

Overhaul & massively expand test suite Reformatted code, added more in-code docs

3.4.1

Converted arrow functions to regular functions to satisfy Webpack + UglifyJS edge case

3.4.0

Revamped so process.env.* vars are directly exposed (for webpack injection)

3.3.0

Cleaner, shorter codebase: helpers generate exported env vars

Module/Library/Engine upgrades:

  • Prettier -> v1.12
  • Typescript -> v2.8.3
  • Node -> v8.10.0
  • ts-node: v5.0.0 -> v6.0.2
  • mocha: v5.0.5 -> v5.1.1
  • nodemon: v1.15.1 -> v1.17.3
  • sinon: v4.4.9 -> v5.0.2

Simplified CHANGELOG format

Build environment / utils:

  • Adds prettier config
  • Adds TSLint & TSLint config
  • Updates tsconfig.json to match new TS version
  • Adds TSLint rules plugins:
    • tslint-eslint-rules
    • tslint-microsoft-contrib
    • vrsource-tslint-rules
  • Adds typings for Mocha, Chai, & Sinon
  • Removed dependencies:
    • detect-node (removed altogether)
    • string.prototype.padend (removed altogether)
    • mad-logs (moved to devDependencies)

New exported types:

  • LogLevel
  • NodeEnv
  • ReleaseEnvs type renamed to ReleaseEnvs

New 'trace' LOG_LEVEL:

  • Adds trace log level (at lowest level)
  • Adds function isTrace (true if LOG_LEVEL=trace)

Adds QA environment:

  • QA functions: isQA, isQa, isReleaseEnvQA, isReleaseEnvQa
  • Adds 'qa' as option to ReleaseEnv & ReleaseEnvShort types
  • Sets releaseEnvShort to 'qa' if detected RELEASE_ENV is QA (RELEASE_ENV=qa)

New release environment detection functions (for existing release environments):

  • isReleaseEnvDev & isReleaseEnvDevelopment
  • isReleaseEnvProd & isReleaseEnvProduction

Tests:

  • Adds LOG_LEVEL=verbose tests
  • Adds LOG_LEVEL=info tests
  • Adds LOG_LEVEL=error tests
  • Adds default LOG_LEVEL tests
  • Adds RELEASE_ENV=qa tests
  • Adds RELEASE_ENV=uat tests
  • Adds RELEASE_ENV=production tests

3.2.0

Ran prettier on main file & other misc cleanups

Proper export method for aliases (export {name as alias})

  • Previous did extraneous duplicate object creations/var assignments & exported

lodash types updated (to 4.14.104)

Typescript -> 2.7.2

3.0.0

Major overhaul

Numerous subtle bugs were fixed, most/all of which were runtime and some of which could hypothetically reach production unnoticed. Some had the potential to result in e.g.:

  • parts of the application silently disappearing;
  • features being shut off
  • development logs becoming visible to end-users
  • the delivery of payloads that exclude browsers the application is required to support
    • due to task runners/transpilers overlooking environment variables that indicate that the build should include additional polyfills and/or extra transpilation steps for supporting less modern browsers). Thus, any usages that relied on broken exported values stop working as expected.

Note that it's still fairly unlikely that many consumers of the library ran into this issue. Almost all of the issues related to the less convenient (albeit usually more accurate) aliases. Also, many (but not all) of these issues are fairly easy to detect if using Typescript. It's more likely that these features would simply not be used (they are rarely used in the internal production codebases for which this was developed), or would be detected in development.

  • I came across only one in our many codebases (which uses exports from this library 1000s of times) and discovered it before it reached production (this is what prompted the audit and repair of this library - the issue was very difficult to detect, and it caused an otherwise inexplicable show-stopping bug that took an extremely long time to trace to env-var-helpers).

There's thus at least some potential for breakage since it's conceivable that someone may have run into our my issue but worked around it, so I felt a full major version upgrade was called for.

Specific issues: 1) The older Mocha and test environment detecting exports relied on a manually set TEST_MODE environment variable. This was documented, but the documentation suggested this is the only thing the library uses for test detection. However, some of the exported properties use environment variable interally set by Mocha. The difference is now clearly identified.

2) If the "process" global variable is undefined, in certain environments the application will crash at runtime (by attempting to access properties of "undefined"). Our client builds inject process.env, and our commonly used environments are unaffected (side note: we inject process.env with a restricted subset of the backend properties. It is extremely dangerous and insecure to inject the entire contents of process.env into a client-side application)

3) If NODE_ENV is set to development or production, but the values are not in lowercase (e.g. NODE_ENV=PRODUCTION), both isDevelopment and isProduction would be outputted as false, causing sections of code to be unexpectedly skipped.

Beyond these fixes, the test suite was overhauled and expanded to provide almost complete coverage (albeit only in a NodeJS environment - run through Mocha). There were numerous subtly broken tests, which have now been repaired.

A set of convenience functions were also added to simulaneously detecting the log level and whether the current process was run by Mocha.