callumlocke / strong-env

Tiny Node.js library for coercing environment variables into strongly typed values
1 stars 0 forks source link

strong-env

Tiny library for loading config from environment variables in Node.js/Bun with strong typing and validation. No dependencies.

Why?

App configuration values are typically a mixture of strings, booleans and numbers. But environment variables are always strings. For example, HTTPS=false results in the string "false", which can cause confusing bugs.

This library safely coerces environment variables into the correct types, throwing an error if any are missing or invalid.

Installation

> npm install strong-env
# Also works with `bun`, `yarn`, `pnpm` etc.

Usage

// e.g. app/config.ts

import env from 'strong-env'

export const USE_HTTPS = env.boolean('USE_HTTPS')
export const DB_PORT = env.port('DB_PORT', 3000)
export const API_HOSTNAME = env.string('API_HOSTNAME', 'https://localhost')

Methods

boolean

Ensures it's a boolean.

number

Ensures it's a finite number.

integer

Like number, but also ensures it's an integer.

port

Like integer, but also ensures it's a valid port number, i.e. 1 through 65535.

string

Ensures it's a non-empty string.

Default type inference

If a default value with a different type is provided, the return type is inferrred accordingly:

env.port('PORT', null);   // number | null

Custom source object

The default export is based on the process.env global (which works in both Node and Bun). If for some reason you want to use a different object as the source, you can do this:

import { load } from 'strong-env'

const myCustomEnv = { 'FOO': '1234' };

const env = load(myCustomEnv)

export const FOO = env.port('FOO')

The load function accepts any plain object typed the same as process.env: { [name: string]: string | undefined }.

Licence

MIT