• Stars
    star
    375
  • Rank 114,096 (Top 3 %)
  • Language
    JavaScript
  • License
    BSD 3-Clause "New...
  • Created almost 6 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A utility for verifying environment variables are present

Env utility

by Nicholas C. Zakas

If you find this useful, please consider supporting my work with a donation.

Description

A utility for verifying that environment variables are present in Node.js, Deno, and Bun. The main use case is to easily throw an error when an environment variable is missing. This is most useful immediately after a Node.js or Deno program has been initiated, to fail fast and let you know that environment variables haven't been setup correctly.

Usage

Node.js

Install using npm or yarn:

npm install @humanwhocodes/env

# or

yarn add @humanwhocodes/env

Import into your Node.js project:

// CommonJS
const { Env } = require("@humanwhocodes/env");

// ESM
import { Env } from "@humanwhocodes/env";

By default, an Env instance will read from process.env.

Deno

Import into your Deno project:

import { Env } from "https://cdn.skypack.dev/@humanwhocodes/env?dts";

By default, an Env instance will read from Deno.env.

Bun

Install using this command:

bun add @humanwhocodes/env

Import into your Bun project:

import { Env } from "@humanwhocodes/env";

By default, an Env instance will read from process.env.

Browser

It's recommended to import the minified version to save bandwidth:

import { Env } from "https://cdn.skypack.dev/@humanwhocodes/env?min";

However, you can also import the unminified version for debugging purposes:

import { Env } from "https://cdn.skypack.dev/@humanwhocodes/env";

By default, an Env instance will read from an empty object.

API

After importing, create a new instance of Env to start reading environment variables:

const env = new Env();

// read a variable and don't care if it's empty
const username = env.get("USERNAME");

// read a variable and use a default if empty
const username = env.get("USERNAME", "humanwhocodes");

// determine if a variable exists
const usernameExists = env.has("USERNAME");

// read the first found variable and use a default is empty
const username = env.first(["USERNAME", "USERNAME2"], "humanwhocodes");

// read a variable and throw an error if it doesn't exist
// or is an empty string
const username = env.require("USERNAME");

// read the first found variable throw an error if none exist
const username = env.requireFirst(["USERNAME", "USERNAME2"]);

To retrieve more than one required environment variable at one time, you can use the required property with destructuring assignment:

const env = new Env();

// throws if variables are undefined or an empty string
const {
    CLIENT_ID,
    CLIENT_SECRET
} = env.required;

In this example, an error is thrown if either CLIENT_ID or CLIENT_SECRET is missing or an empty string. The required property is a proxy object that throws an error whenever you attempt to access a property that doesn't exist.

If you don't want to throw an error for environment variables containing an empty string, use the exists property:

const env = new Env();

// throws only if variables are not defined
const {
    CLIENT_ID,
    CLIENT_SECRET
} = env.exists;

You can also specify an alternate object to read variables from. This can be useful for testing or in the browser (where there is no environment variable to read from by default):

const env = new Env({
    USERNAME: "humanwhocodes"
});

// read a variable and don't care if it's empty
const username = env.get("USERNAME");

// read a variable and throw an error if it doesn't exist
const password = env.require("PASSWORD");

Last, you can specify custom error classes to throw for the two different types of errors: key not found and empty string. Each error constructor is passed the string key that caused the error. Here's an example:

class MyKeyNotFoundError extends Error {
    constructor(key) {
        super(`Yo this key isn't here: ${key}.`);
    }
}

class MyEmptyStringError extends Error {
    constructor(key) {
        super(`Hey! This key is empty: ${key}.`);
    }
}

Env.KeyNotFoundError = MyKeyNotFoundError;
Env.EmptyStringError = MyEmptyStringError;

Note that changing the error classes affects all instances of Env, both those that are already created and those that will be created within the same lifetime.

Developer Setup

  1. Fork the repository
  2. Clone your fork
  3. Run npm install to setup dependencies
  4. Run npm test to run tests

License

BSD 3-Clause

More Repositories

1

computer-science-in-javascript

Collection of classic computer science paradigms, algorithms, and approaches written in JavaScript.
JavaScript
9,059
star
2

humanfs

A modern filesystem API for JavaScript
JavaScript
486
star
3

momoa

A JSON parser, tokenizer, traverser, and printer.
JavaScript
313
star
4

print-ready

A JavaScript-powered CLI for converting HTML into PDFs
JavaScript
115
star
5

pledge

A custom promise implementation for JavaScript
JavaScript
90
star
6

puppeteer-data-extractor

JavaScript
46
star
7

object-schema

DEPRECATED. Use eslint/object-schema instead.
JavaScript
32
star
8

config-array

DEPRECATED. Use eslint/config-array instead
JavaScript
30
star
9

number-to-words

A JavaScript function to convert a number into words
JavaScript
30
star
10

tweet

A CLI for posting to Twitter
JavaScript
28
star
11

module-importer

Universal importer for CommonJS and ESM in Node.js
JavaScript
26
star
12

eslint-simple-rule

A utility for creating simple ESLint rules
JavaScript
23
star
13

async-event-emitter

Asynchronous version of EventEmitter for JavaScript
JavaScript
20
star
14

retry

A JavaScript utility for retrying async methods that reject errors
JavaScript
19
star
15

gitignore-to-minimatch

Utility to convert gitignore patterns into minimatch patterns
JavaScript
11
star
16

astro-jekyll

Toolkit to make transferring a Jekyll website to Astro simple!
JavaScript
9
star
17

toot

CLI for posting to Mastodon
JavaScript
9
star
18

humanwhocodes.com

HTML
8
star
19

ordered-set

A set data structure that maintains the order of insertion
JavaScript
8
star
20

object-store

JavaScript
8
star
21

array-with-default

An implementation of Array with a default for missing values
JavaScript
7
star
22

github-comment

A simple CLI for posting comments to GitHub issues and pull requests
JavaScript
6
star
23

memory

A JavaScript implementation of dynamic memory.
JavaScript
5
star
24

disqus-export

Disqus comments exporter
JavaScript
2
star
25

hello-nodejs-service

A simple microservice as an example for running Node.js on Google Cloud Run
JavaScript
2
star
26

hello-deno-service

An example Deno service to run on Google Cloud Run
JavaScript
2
star
27

markdown-it-markua-aside

markdown-it plugin for Markua asides and blurbs
JavaScript
1
star