Skip to content
This repository has been archived by the owner on Apr 8, 2024. It is now read-only.
/ safe-env Public archive

Small library to load strongly typed values from environment variables

License

Notifications You must be signed in to change notification settings

Coder-Spirit/safe-env

Repository files navigation

@coderspirit/safe-env

Warning

We moved the project to another repository: https://github.com/coder-spirit/nominal/ to improve its maintenance (the NPM package is still the same).

NPM version TypeScript License npm downloads Known Vulnerabilities Security Score

Small library to load strongly typed values from environment variables

Install instructions

Node

# With NPM
npm install @coderspirit/safe-env

# Or with Yarn:
yarn add @coderspirit/safe-env

Safe-Env is served through different CDNs

import { ... } from 'https://denopkg.com/Coder-Spirit/safe-env@[VERSION]/safe-env/deno/index.ts'
import { ... } from 'https://deno.land/x/safe_env@[VERSION]/safe-env/deno/index.ts'

Example

import { getSafeEnv } from '@coderspirit/safe-env'

const safeEnv = getSafeEnv(process.env) // For NodeJS
// const safeEnv = getSafeEnv(Deno.env.toObject()) // For Deno

// If there's no default, the value is considered as required, and it will throw
// an exception when it's missing.
const myVariable = safeEnv.asString('MY_VARIABLE')

// We can provide defaults, so no exception will be thrown when the environment
// variable is not set.
const myVariable = safeEnv.asString('MY_VARIABLE', 'hello world')

// We can parse numbers, with some constraints
const myNumber = safeEnv.asNumber('MY_NUMBER')
const myPositiveNumber = safeEnv.asPositiveNumber('MY_POSITIVE_NUMBER')
const myInteger = safeEnv.asInteger('MY_INTEGER')
const myPositiveInteger = safeEnv.asPositiveInteger('MY_POSITIVE_INTEGER')

// We can also parse "boolean" values, It will understand:
// true, yes, 1; false, no, 0; in a case-insensitive way.
const myBoolean = safeEnv.asBoolean('MY_BOOLEAN')