envalid - validate your required environment variables

Environment Variables (bash)

In the software world - thanks to people who create and maintain open source libraries - there aren’t many problems that aren’t already solved.

In my quest to manage required environment variables for my Node.js applications, I stumbled upon envalid - a neat utility to ensure that all necessary variables are set before bootstrapping the application.

Manual validation

1
2
3
4
5
6
7
8
9
const cachePath = process.env.CACHE_PATH;
if(typeof cachePath === 'string') {
// Perform other validations
} else {
console.error('Missing CACHE_PATH environment variable.');
process.exit(1);
}

// Repeat for more variables

With envalid

1
2
3
4
5
6
const {cleanEnv, str} = require('envalid');

// Verify required environment variables
const env = cleanEnv(process.env, {
CACHE_PATH: str(),
});

Custom validators

Further, envalid supports custom validators to add additional checks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const { makeValidator } = require('envalid');
const fs = require('fs');
const path = require('path');
const {cleanEnv, str} = require('envalid');

const exists = makeValidator(x => {
// Correct path according to current platform
const normalized = path.normalize(x);
if (fs.existsSync(normalized)) {
return normalized;
} else {
throw new Error('Directory does not exist.');
}
}, 'exists');

const env = cleanEnv(process.env, {
CACHE_PATH: exists(),
});

console.log(env.CACHE_PATH);

Further

If you require custom error reporting, you can read more about it.

Share