ENV Utils

Easily Get Environment Variables
Install
yarn add @bolajiolajide/env-utils
getEnvVar
Gets an environment variable. This returns an error if the environment variable isn't detected.
import getEnvVar from 'env-utils';
getEnvVar(envVarName, options);
Options
options.isBoolean - Forces the value to be a boolean
const shouldAcceptCoins = getEnvVar('SHOULD_ACCEPT_COINS', { boolean: true });
options.isArray - If your env variable is a comma separated string you can get back an array instead.
const PORTS = getEnvVar('PORTS', { isArray: true });
In the event that the variable is separated by something other than a comma, you can define the separator using options.separator.
const PORTS = getEnvVar('PORTS', { isArray: true, separator: '&' });
options.devDefault - used to specify a development-environment-only fallback for the variable. If the variable is undefined, the devDefault is returned in it's stead.
This only applies when process.env.NODE_ENV === 'development'. Any other value of NODE_ENV will not regard this option
const PORT = getEnvVar('PORT', { devDefault: '1234'});
options.optional - Used to identify variables that are optional. This is specifically useful when you don't want an error thrown for undefined variables.
const SOMETHING = getEnvVar('SOMETHING', { optional: true });
options.isNumber - used to convert numeric-like variables into number. Note: This will throw an error if it's true and the variable isn't numeric-like.
const PORT = getEnvVar('PORT', { isNumber: true });
const PORT = getEnvVar('PORT', { isNumber: true });
Lazy Fetching an environment variable
You can lazy fetch an environment variable using the function below, it's a result of composing the getEnvVar method:
const lazyGetEnvVar = (...args) => () => getEnvVar(...args);
Utility Functions
env-utils exports some utility functions that return variables in a certain type. This is especially useful for typescript projects, so you don't have to deal with type casting with the as keyword.
Below is an example:
import getEnvVar, { getStringEnv, getNumericEnv } from '@bolajiolajide/env-utils';
getEnvVar('SENTRY_DSN')
getStringEnv('SENTRY_DSN')
N.B All utility functions have exactly the same signature as the getEnvVar function, along with some overrides that ensures that there are no implicit type conversion/casting.
getStringEnv returns an environment variable as a string
getArrayEnv<T> returns an environment variable as an array, can be passed a generic to identify the type of the array's content
getBoolEnv returns an environment variable as a boolean
getNumericEnv returns an environment variable as a number
This works great with the lazy-config module.
Hello World