Ensure Required ENV Variables Are Set in Node.js

October 25, 2016

If you use the widely recommended best practice of putting your applicationĀ configuration in environment variables, then you have probably also run into the problem of ensuring certain environment variables are set that are required for your application to function – such as transactional email API keys or your database connection settings.

With the most popular dotenv package on NPM, validation thatĀ certain ENV variables have been setĀ is not built-in, so I came up with this easy way to ensure that all the required environment variables are set in my Node.js app, ensuring error-free deploys to any environment:

const dotenv = require('dotenv');

// Config / .env

// Ensure required ENV vars are set
let requiredEnv = [
let unsetEnv = requiredEnv.filter((env) => !(typeof process.env[env] !== 'undefined'));

if (unsetEnv.length > 0) {
  throw new Error("Required ENV variables are not set: [" + unsetEnv.join(', ') + "]");

It checks that all provided variables are set, and tells you exactly which ones are not set if it can’t find them. Easy, right?

Tags: , ,

Categories: ,