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

Package detail

env-var

evanshortiss1.3mMIT7.5.0TypeScript support: included

Verification, sanitization, and type coercion for environment variables in Node.js

dotenv, env, process.env, process, var, environment, variables, variable, loader, env-var, envvar, config, configuration, typescript, ts

readme

env-var

NPM version TypeScript License Coverage Status npm downloads Known Vulnerabilities

Verification, sanitization, and type coercion for environment variables in Node.js and web applications. Supports TypeScript!

  • 🏋 Lightweight. Zero dependencies and just ~4.7kB when minified!
  • 🧹 Clean and simple code, as shown here.
  • 🚫 Fails fast if your environment is misconfigured.
  • 👩‍💻 Friendly error messages and example values for better debugging experience.
  • 🎉 TypeScript support provides compile time safety and better developer experience.
  • 📦 Support for frontend projects, e.g in React, React Native, Angular, etc.

Contents

Install

npm

npm install env-var

yarn

yarn add env-var

Getting started

You can use env-var in both JavaScript and TypeScript!

Node.js Javascript example

const env = require('env-var');

// Or using module import syntax:
// import env from 'env-var'

const PASSWORD = env.get('DB_PASSWORD')
  // Throws an error if the DB_PASSWORD variable is not set (optional)
  .required()
  // Decode DB_PASSWORD from base64 to a utf8 string (optional)
  .convertFromBase64()
  // Call asString (or other APIs) to get the variable value (required)
  .asString();

// Read in a port (checks that PORT is in the range 0 to 65535)
// Alternatively, use a default value of 5432 if PORT is not defined
const PORT = env.get('PORT').default('5432').asPortNumber()

Node.js TypeScript example

import * as env from 'env-var';

// Read a PORT environment variable and ensure it's a positive integer.
// An EnvVarError will be thrown if the variable is not set, or if it
// is not a positive integer.
const PORT: number = env.get('PORT').required().asIntPositive();

WebApp Example

When using environment variables in a web application, usually your tooling such as vite imposes special conventions and doesn't expose process.env. Use from function to workaround this, and create an env object like so:

import { from } from 'env-var'

const env = from({
  BASE_URL: import.meta.env.BASE_URL,
  VITE_CUSTOM_VARIABLE: import.meta.env.CUSTOM_VARIABLE
})

For more examples, refer to the /example directory and EXAMPLE.md. A summary of the examples available in /example is written in the 'Other examples' section of EXAMPLE.md.

API

The examples above only cover a very small set of env-var API calls. There are many others such as asFloatPositive(), asJson() and asRegExp(). For a full list of env-var API calls, check out API.md.

You can also create your own custom accessor; refer to the 'extraAccessors' section of API.md.

Logging

Logging is disabled by default in env-var to prevent accidental logging of secrets.

To enable logging, you need to create an env-var instance using the from() function that the API provides and pass in a logger.

  • A built-in logger is available, but a custom logger is also supported.
  • Always exercise caution when logging environment variables!

Using the Built-in Logger

The built-in logger will print logs only when NODE_ENV is not set to either prod or production.

const { from, logger } =  require('env-var')
const env = from(process.env, {}, logger)

const API_KEY = env.get('API_KEY').required().asString()

This is an example output from the built-in logger generated by running example/logging.js:

logging example output

Using a Custom Logger

If you need to filter env-var logs based on log levels (e.g. trace logging only) or have your own preferred logger, you can use a custom logging solution such as pino easily.

See the 'Custom logging' section of EXAMPLE.md for more information.

Optional integration with dotenv

You can optionally use dotenv with env-var.

There is no coupling between dotenv and env-var, but you can easily use them both together. This loose coupling reduces package bloat and allows you to start or stop using one without being forced to do the same for the other.

See the 'dotenv' section of EXAMPLE.md for more information.

Contributing

Contributions are welcomed and discussed in CONTRIBUTING.md. If you would like to discuss an idea, open an issue or a PR with an initial implementation.

Contributors

  • @aautio
  • @avocadomaster
  • @caccialdo
  • @ChibiBlasphem
  • @DigiPie
  • @dror-weiss
  • @evanshortiss
  • @gabrieloczkowski
  • @hhravn
  • @ineentho
  • @itavy
  • @jerome-fox
  • @joh-klein
  • @Lioness100
  • @MikeyBurkman
  • @pepakriz
  • @rmblstrp
  • @shawnmclean
  • @todofixthis
  • @xuo

changelog

7.5.0 (20/05/2024)

  • Add AsSet() accessor (#173)

7.4.2 (10/05/2024)

  • Fix docstrings for positive/negative int/float validators (#172)

7.4.1 (29/08/2023)

  • Fix 7.4.0 issues with create-react-app polyfill (#168)

7.4.0 (21/08/2023)

  • Do not use process.env by default in non-Node.js environments (#155)

7.3.1 (24/04/2023)

  • Fix parsing even floating point numbers (#166)

7.3.0 (06/09/2022)

  • Add missing asEmailString() typings (#160)

7.2.0 (01/09/2022)

  • Add asEmailString() accessor (#146)

7.1.1 (28/10/2021)

  • Fix duplicate identifier error for TypeScript builds (#151)

7.1.0 (28/10/2021)

  • Support type narrowed process.env/record and remove unused type (#148)
  • Add support for readonly T[] generic use with asEnum()

7.0.1

  • Fix loose float and int parsing (PR #144)

7.0.0 (11/11/2020)

  • Drop support for Node.js 8 and 13 (support only current, active, and maintenance versions)
  • Improve support for browser usage (#138)
  • Fix documentation errors (#139)

6.3.0 (27/07/2020)

  • Add asRegExp accessor (#136)
  • Add better TypeScript example for custom accessors (#133)

6.2.0 (12/06/2020)

  • Add accessors property to the public API for use in building extraAccessors (#121)
  • Add support for logging with a built-in or custom logger (#112)
  • Add Node.js v14 to CI builds
  • Add single quote rule to .editorconfig (#129)
  • Add JavaScript example for extraAccesors (#129)
  • Fix extraAccessors args type error (#131)
  • Fix types and docs for asUrlString() and asUrlObject() (#132)
  • Update README for asUrlString() to mention WHATWG URL behaviour (#126, #129)

6.1.1 (22/04/2020)

  • Fix TS error with ExtenderTypeOptional and ExtenderType typings (#119)

6.1.0 (20/04/2020)

  • Fix TS error with extraAccessor typings (#114)
  • Add support for generic types in asEnum (#116)

6.0.4 (04/03/2020)

  • Fix compilation error caused by typings generic issue.

6.0.3 (03/03/2020)

  • Fix typings to support required(), convertFromBase64(), etc. with ExtensionFn.

6.0.2 (29/02/2020)

  • Fix default() so that it correctly returns an empty string value if provided.
  • README improvement by @joh-klein for positive/negative number parsing rules.

6.0.1 (12/02/2020)

  • Fix typings for the default(value) function.

6.0.0 (12/02/2020)

  • Add support for setting an example value via the example(string) function.
  • Passing default values is now performed using the default(string) function.
  • Defer checks for required() until an accessor such as asString() is invoked.
  • Fix typings issue where required() was undefined on a IPresentVariable.
  • Improve error message output.

Migration from 5.x to 6.0.0 should be smooth. Change any instance of env.get(target, default) to env.get(target).default(default). For example:

// Old 5.x code
const emailAddr = env.get('EMAIL_ADDR', 'admin@example.com').asString()

// New 6.x compatible code
const emailAddr = env.get('EMAIL_ADDR').default('admin@example.com').asString()

5.2.0 (22/11/2019)

  • The required() function now verifies the variable is not an empty string

5.1.0 (09/09/2019)

  • Ability to add custom accessors in PR #72 (thanks @todofixthis)
  • Improved TypeScript tests
  • Fixed warning generated by husky

5.0.0 (14/06/2019)

  • Return values from asArray() are now more intuitive & consitent
  • asUrlString() and asUrlObjectnow use the built-in URL class in Node.js to perform validation
  • README updated in accordance with changes listed above

4.1.0 (14/06/2019)

  • Add asPortNumber() function
  • Update documentation structure

4.0.1 (24/05/2019)

  • Add node process.env typings to env.from

4.0.0 (09/04/2019)

  • Rename .env.mock() to env.from()
  • Change module internals per issue #39
  • Update docs related to env.mock

3.5.0 (02/29/2019)

  • Update required() to support boolean paramter to bypass the check

3.4.2 (06/11/2018)

  • Fix README badge copy/paste error

3.4.1 (06/11/2018)

  • Fix TypeScript definition for "asBoolStrict" function name

3.4.0 (24/10/2018)

  • Add convertFromBase64() function
  • Enable Greenkeeper

3.3.0 (26/06/2018)

  • Add asEnum functionality

3.2.0 (15/06/2018)

  • Remove @types/node dependency

3.1.0 (11/12/2017)

  • Update typings to correctly handle default values for numeric types.
  • Ensure an error is thrown when asArray does not detect at least a single non-empty value.

3.0.2 (19/10/2017)

  • Restore support for use in browser based applications

3.0.1 (19/10/2017)

  • Fix bug that caused default values to be ignored

3.0.0 (13/10/2017)

  • Public API no longer is a function, instead exposes two functions, mock and get
  • Drop support for Node.js versions less than 4.0
  • Rename asPositiveInt to asIntPositive
  • Rename asNegativeInt to asIntNegative
  • Rename asStrictBool to asBoolStrict
  • Add asFloatPositive and asFloatNegative
  • Add asUrlString and asUrlObject
  • Refactor code with consistent errors and structure
  • Use standard for code quality and formatting

2.4.3 (5/04/2017)

  • Update with build, coverage, and version information badges

2.4.2 (19/12/2016)

  • Fix TypeScript definition file

2.4.1 (15/12/2016)

  • Remove unnecessary code path

2.4.0 (15/12/2016)

  • Add asArray([delimeter]) to read environment variables as an array by splitting the varible string on each instance of delimeter;
  • Add asJsonArray() to read in an environment variable that contains a JSON Array. Similar to asJson(), but ensures the variable is an Array.
  • Add asJsonObject() to read in an environment variable that contains a JSON Object. Similar to asJson(), but ensures the variable is an Object.

2.3.0 & 2.3.1 (12/12/2016)

  • Add typings support for TypeScript

2.2.0 (28/10/2016)

  • Thanks to @itavy for a patch for our asBool parsing and adding the new asStrictBool function

2.1.0 (25/10/2016)

  • Added env.mock PR from @MikeyBurkman to improve testability

2.0.0 (27/07/2016)

  • Add CI process for node 6, 5, 4, and 0.10
  • Add chained functions for variable validations
  • Add assertions for required() and various type checks, e.g asPositiveInt()
  • Remove node 0.8.x support
  • Remove old pattern of returning variables directly
  • Continue support for defaults from 1.X

<2.0.0

  • Venture forth at thine own risk, for here be dragons