Ensure Required ENV Variables Are Set in Node.js

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
dotenv.load();

// Ensure required ENV vars are set
let requiredEnv = [
  'NODE_ENV', 'DATABASE_URL',
  'GOOGLE_PLACES_API_KEY', 'ROLLBAR_SERVER_API_KEY',
  'MAILGUN_API_URL', 'MAILGUN_API_KEY'
];
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?