• Stars
    star
    767
  • Rank 57,209 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated 12 months ago

Reviews

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

Repository Details

πŸ”’ Makes sure you don't accidentally deploy apps with missing or invalid environment variables.

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.

========================================
❌ Invalid environment variables:
    API_URL: Invalid url input: "http//example.com/graphql"
πŸ’¨ Missing environment variables:
    MY_VAR: Missing value or empty string
    PORT: Missing value or empty string
========================================

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

How to use

Works the same in the browser and in node. See the ./examples-folder for more examples.

Install

yarn add envsafe
npm i envsafe --save

Basic usage

import { str, envsafe, port, url } from 'envsafe';

export const env = envsafe({
  NODE_ENV: str({
    devDefault: 'development',
    choices: ['development', 'test', 'production'],
  }),
  PORT: port({
    devDefault: 3000,
    desc: 'The port the app is running on',
    example: 80,
  }),
  API_URL: url({
    devDefault: 'https://example.com/graphql',
  }),
  AUTH0_CLIENT_ID: str({
    devDefault: 'xxxxx',
  }),
  AUTH0_DOMAIN: str({
    devDefault: 'xxxxx.auth0.com',
  }),
});

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

export const env = envsafe(
  {
    ENV_VAR: str({
      devDefault: 'myvar',
    }),
  },
  {
    env: window.__ENVIRONMENT__,
  },
);

Built-in validators

Function return value Description
str() string Passes string values through, will ensure an value is present unless a default value is given.
bool() boolean Parses env var strings "0", "1", "true", "false", "t", "f" into booleans
num() number Parses an env var (eg. "42", "0.23", "1e5") into a Number
port() number Ensures an env var is a TCP port (1-65535)
url() string Ensures an env var is a url with a protocol and hostname
email() string Ensures an env var is an email address
json() unknown Parses an env var with JSON.parse

Possible options

All optional.

Name Type Description
choices TValue[] Allow-list for values
default TValue / string A fallback value, which will be used if the env var wasn't specified. Providing a default effectively makes the env var optional.
devDefault TValue / string A fallback value to use only when NODE_ENV is not production. This is handy for env vars that are required for production environments, but optional for development and testing.
input string As some environments don't allow you to dynamically read env vars, we can manually put it in as well. Example
allowEmpty boolean Default behavior is false which treats empty strings as the value is missing; if explicit empty strings are OK, pass in true.

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

Name Type Description
desc string A string that describes the env var.
example string / TValue An example value for the env var.
docs string A url that leads to more detailed documentation about the env var.

Custom validators/parsers

import { makeValidator, envsafe } from 'envsafe';

const barParser = makeValidator<'bar'>(input => {
  if (input !== 'bar') {
    throw new InvalidEnvError(`Expected '${input}' to be 'bar'`);
  }
  return 'bar';
});

const env = envsafe({
  FOO: barParser(),
});

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

const env = envsafe(
  {
    MY_VAR: str(),
  },
  {
    reporter({ errors, output, env }) {
      // do stuff
    },
  },
);

Strict mode (recommended for JS-users)

By default envsafe returns a Readonly<T> 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.

import { envsafe, str } from 'envsafe';

export const browserEnv = envsafe(
  {
    MY_ENV: str(),
  },
  {
    strict: true,
  },
);

More Repositories

1

shop

πŸ›πŸ›’ Full-stack React/Prisma/TS/GraphQL E-Commerce Example
TypeScript
374
star
2

zart

🀯 zART-stack β€” Zero-API, React [Native], & TypeScript
TypeScript
303
star
3

typescript.careers

TypeScript
39
star
4

next-router-query

πŸ‘¨β€πŸ”§ Drop-in alternative of `useRouter().query` that tries it's best to get the query params on the first mount.
TypeScript
38
star
5

graphql-workshop

πŸ•ΈοΈ GraphQL Node.js Workshop: Create an API Gateway
JavaScript
21
star
6

next-with-apollo-airbnb-auth0-graphcool

Server-side rendered & authed requests with GraphQL
JavaScript
13
star
7

next-ssr-form

next-ssr-form
TypeScript
12
star
8

options-curry

πŸ› TypeScript Options-object Currying
TypeScript
11
star
9

use-is-typing

… React Hook for typing indicator
TypeScript
9
star
10

toggl-iCal

πŸ“…β³ Calendar Toggl Entries
TypeScript
9
star
11

resident-advisor-resale-checker

🎟 Resident Advisor Resale checker
TypeScript
9
star
12

useSuspense-next-prisma-starter

TypeScript
9
star
13

next-use-query-params

TypeScript
9
star
14

gitkatt

πŸ‘¨β€πŸŽ€ create art in your github commit history
JavaScript
8
star
15

app-dir-play

TypeScript
6
star
16

Magento-CustomerLogin

Login as any customer easily from customer grid in admin. Not actually working, see stackoverflow-link.
PHP
6
star
17

brunch-jade-stylus-coffee

Bare-bones brunch skeleton using Stylus, Jade and CoffeeScript
CSS
5
star
18

500cats

😻 Pointless TypeScript/nextjs/s3/imgix project
TypeScript
5
star
19

create-react-app-docz-test

Example of create-react-app with absolute imports + docz
JavaScript
4
star
20

typed-form

typesafe formik example
TypeScript
3
star
21

nextjs-13-use-client

CSS
2
star
22

next-trpc-form-proc

TypeScript
2
star
23

awilix-typescript-dependency-injection

TypeScript
2
star
24

mfn

TypeScript
2
star
25

sanitize-object-deep-by-regex

TypeScript
1
star
26

trpc-declaration

TypeScript
1
star
27

forked-versions

TypeScript
1
star
28

unidici-fetch-reserved-header-crap

TypeScript
1
star
29

clubmate

nodejs fest
JavaScript
1
star
30

my-vite-bling-react-app

play around with vite + bling
TypeScript
1
star
31

goaskamt

JavaScript
1
star
32

AJFormViewController

Objective-C
1
star
33

boilerplate-heroku-static-nodejs-express-basic-auth

Boilerplate static web app Heroku + Basic auth setup
JavaScript
1
star
34

trpc-rsc

TypeScript
1
star
35

promise-click

JavaScript
1
star
36

lectr

JavaScript
1
star
37

trpc-ssr-form

TypeScript
1
star
38

iOSBase

future base of my ios applications
Objective-C
1
star
39

AJScrollableView

Objective-C
1
star
40

react-server-action-useformstate-issues

Just a repo showcasing some issues with the design of Server Actions / `useActionState` /`useFormState()`
TypeScript
1
star
41

yarn-workspaces-lerna-mono-server-client

JavaScript
1
star
42

wizzy

TypeScript
1
star