npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@baileyherbert/env

v3.0.0

Published

Read and validate environment variables with a typed schema.

Downloads

25

Readme

Env

This package makes it simple to retrieve, manage, validate, and assign types to environment variables.

Installation

npm install @baileyherbert/env

After installing the package, you can import the global Env variable which automatically reads environment variables from process.env, as well as from a .env file in the current working directory if it exists.

import { Env } from '@baileyherbert/env';

Documentation

Get values

Retrieve the raw string value of a variable (or undefined if not set):

Env.get('VARNAME');

Retrieve the value of a variable with a default value. The string value will be converted to the same type as the default value:

Env.get('VARNAME', 0); // always a number
Env.get('VARNAME', false); // always a boolean

Note that if a default value is supplied, and the value of the variable cannot be converted to that type, an instance of EnvironmentValidationError will be thrown.

Validation

In most cases, you should have a file within your application that defines all known environment variables and their acceptable format, like below:

export const Environment = Env.rules({
    DRIVER: Env.schema.enum(['mysql', 'sqlite']),
    HOSTNAME: Env.schema.string().optional('localhost'),
    PORT: Env.schema.number().optional(3306),
    USERNAME: Env.schema.string(),
    PASSWORD: Env.schema.string()
});

You can then import the file across your application and retrieve the parsed values:

const driver = Environment.DRIVER; // 'mysql' | 'sqlite'
const host = Environment.HOSTNAME; // string

String variables

Env.schema.string()

Number variables

Env.schema.number()

Boolean variables

Env.schema.boolean()

Enum variables

You can enumerate acceptable strings or numbers directly by passing an array of values.

Env.schema.enum(['option1', 'option2', ...])

You can also supply an actual enum object, which supports both string and number values. Note that users must specify a value from the enumeration rather than a key.

enum StringValues { A = 'a', B = 'a' };
enum NumberValues { A = 0, B = 1 };

Env.schema.enum(StringValues) // 'a' or 'b'
Env.schema.enum(NumberValues) // '0' or '1'

When supplying an enum object, user input is only matched against keys by default. The second parameter can be set to true to enable matching against values as well.

Env.schema.enum(NumberValues) // Acceptable inputs: "A", "B"
Env.schema.enum(NumberValues, true) // Acceptable inputs: "A", "B", "0", "1"

Finally, enum variables expose an allowPartial() method which enables partial matching. For example, if the enum for a logging level contains information, then partial matching would allow the user to specify info. This only works if the partial matches a single key (or value, when enabled).

Env.schema.enum(LogLevel).allowPartial()

Optional variables

To mark an environment variable as optional, call the optional() method on it. This will automatically add undefined to the union type in your final environment object.

Env.schema.string().optional()

You can also provide a default value, which will avoid adding undefined to the union type.

Env.schema.string().optional('default')

Conditional variables

The when() method can be used to define a variable that won't be read or parsed except under certain conditions. Pass a callback function which returns a boolean. The function will receive an object containing all parsed variables up to that point in the schema.

Env.schema.string().when(e => e.BOOLEAN_VARIABLE)
Env.schema.string().when(e => e.STRING_VARIABLE === 'target_value')

If the conditional function returns false, the variable will resolve to undefined by default. You can override this default value using the optional() method.

Env.schema.string().when(e => e.BOOLEAN_VARIABLE).option('default')

Disable the .env file

You can set the ENV_SILENT environment variable on the process to disable the automatic .env file.

ENV_SILENT=true

Change the .env file location

You can set the ENV_PATH environment variable to change the path for the default manager's file source.

ENV_PATH=.env