Validate node environment variables

Usage no npm install needed!

<script type="module">
  import valboValidateEnv from 'https://cdn.skypack.dev/@valbo/validate-env';



Validate node environment variables

npm (scoped) semantic-release Build Status Coverage Status Known Vulnerabilities


npm install @valbo/validate-env


Import this package and specify which environment variables are required and which ones are optional:

import { requiredEnv, optionalEnv } from '@valbo/validate-env';

process.env.PORT = '3001';
process.env.MONGODB_URI = 'mongodb://localhost:27017';
process.env.DATABASE_NAME = 'tests';
process.env.LOG_TAG = 'development';

export const env = {
  ...requiredEnv('PORT', 'MONGODB_URI', 'DATABASE_NAME'),

export type Env = typeof env;

In the above example the Env type is equivalent to:

export type Env = {
  PORT: string;
  MONGODB_URI: string;
  DATABASE_NAME: string;
  LOG_TAG: string | undefined;

The requiredEnv() function will throw when any of the specified environment variables are missing:

import { requiredEnv } from '@valbo/validate-env';

process.env.PORT = '3001';

export const env = requiredEnv('PORT', 'MONGODB_URI', 'DATABASE_NAME');
// throws error "missing required environment variables MONGODB_URI, DATABASE_NAME"