envsafe

Makes sure you don't accidentally deploy apps with missing or invalid envir...

README

Maintainability Test Coverage

envsafe 🔒


Validate access to environment variables and parse them to the right type. Makes sure you don't accidentally deploy apps with missing or invalid environment variables.

  1. ```
  2. ========================================
  3. Invalid environment variables:
  4.     API_URL: Invalid url input: "http//example.com/graphql"
  5. Missing environment variables:
  6.     MY_VAR: Missing value or empty string
  7.     PORT: Missing value or empty string
  8. ========================================
  9. ```

Heavily inspired by the great project envalid, but with some key differences:

- Written in 100% TypeScript
- Always strict - only access the variables you have defined
- Built for node.js and the browser
- No dependencies - tiny bundle for browser/isomorphic apps


  - Install

How to use


Works the same in the browser and in node. See the [./examples](./examples)-folder for more examples.

Install


  1. ```sh
  2. yarn add envsafe
  3. ```

  1. ```sh
  2. npm i envsafe --save
  3. ```

Basic usage


  1. ```ts
  2. import { str, envsafe, port, url } from 'envsafe';

  3. export const env = envsafe({
  4.   NODE_ENV: str({
  5.     devDefault: 'development',
  6.     choices: ['development', 'test', 'production'],
  7.   }),
  8.   PORT: port({
  9.     devDefault: 3000,
  10.     desc: 'The port the app is running on',
  11.     example: 80,
  12.   }),
  13.   API_URL: url({
  14.     devDefault: 'https://example.com/graphql',
  15.   }),
  16.   AUTH0_CLIENT_ID: str({
  17.     devDefault: 'xxxxx',
  18.   }),
  19.   AUTH0_DOMAIN: str({
  20.     devDefault: 'xxxxx.auth0.com',
  21.   }),
  22. });
  23. ```

It defaults to using process.env as a base for plucking the vars, but it can be overridden like this:

  1. ```ts
  2. export const env = envsafe(
  3.   {
  4.     ENV_VAR: str({
  5.       devDefault: 'myvar',
  6.     }),
  7.   },
  8.   {
  9.     env: window.__ENVIRONMENT__,
  10.   },
  11. );
  12. ```

Built-in validators


FunctionreturnDescription
---------------------------------------------------------------------------------------------------------------------
`str()``string`Passes
`bool()``boolean`Parses
`num()``number`Parses
`port()``number`Ensures
`url()``string`Ensures
`email()``string`Ensures
`json()``unknown`Parses

Possible options


All optional.

NameTypeDescription
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
`choices``TValue[]`Allow-list
`default``TValue`A
`devDefault``TValue`A
`input``string`As
`allowEmpty``boolean`Default

These values below are not used by the library and only for description of the variables.

NameTypeDescription
----------------------------------------------------------------------------------------------
`desc``string`A
`example``string`An
`docs``string`A

Custom validators/parsers


  1. ```ts
  2. import { makeValidator, envsafe } from 'envsafe';

  3. const barParser = makeValidator<'bar'>(input => {
  4.   if (input !== 'bar') {
  5.     throw new InvalidEnvError(`Expected '${input}' to be 'bar'`);
  6.   }
  7.   return 'bar';
  8. });

  9. const env = envsafe({
  10.   FOO: barParser(),
  11. });
  12. ```

Error reporting


By default the reporter will

- Make a readable summary of your issues
- console.error-log an error
- window.alert() with information about the missing envrionment variable if you're in the browser
- Throws an error (will exit the process with a code 1 in node)

Can be overridden by the reporter-property

  1. ```ts
  2. const env = envsafe(
  3.   {
  4.     MY_VAR: str(),
  5.   },
  6.   {
  7.     reporter({ errors, output, env }) {
  8.       // do stuff
  9.     },
  10.   },
  11. );
  12. ```

Strict mode (recommended for JS-users)


By default envsafe returns a `Readonly` which in TypeScript ensures the env can't be modified and undefined properties from being accessed, but if you're using JavaScript you are still able to access env vars that don't exist. Therefore there's a strict mode option, which is recommended if your project is using vanilla JS, but not recommended if you use TypeScript.

It wraps the function in Object.freeze and a Proxy that disallows access to any props that aren't defined.

  1. ``` js
  2. import { envsafe, str } from 'envsafe';

  3. export const browserEnv = envsafe(
  4.   {
  5.     MY_ENV: str(),
  6.   },
  7.   {
  8.     strict: true,
  9.   },
  10. );
  11. ```