What is env-var?
The env-var npm package is a utility for accessing and validating environment variables in Node.js applications. It provides a simple and consistent API for retrieving environment variables, ensuring they meet specified criteria, and handling default values.
What are env-var's main functionalities?
Accessing Environment Variables
This feature allows you to access environment variables and convert them to the desired type. In this example, the 'PORT' environment variable is retrieved and converted to a positive integer.
const env = require('env-var');
const port = env.get('PORT').asIntPositive();
console.log(`Server running on port: ${port}`);
Default Values
This feature allows you to specify default values for environment variables. If the 'HOST' environment variable is not set, it defaults to 'localhost'.
const env = require('env-var');
const host = env.get('HOST').default('localhost').asString();
console.log(`Server running on host: ${host}`);
Validation
This feature ensures that certain environment variables are set and meet specified criteria. In this example, the 'API_KEY' environment variable is required and must be a string.
const env = require('env-var');
const apiKey = env.get('API_KEY').required().asString();
console.log(`API Key: ${apiKey}`);
Custom Validators
This feature allows you to define custom validation logic for environment variables. In this example, the 'CUSTOM_VAR' environment variable must start with 'custom-'.
const env = require('env-var');
const customValidator = (value) => value.startsWith('custom-');
const customVar = env.get('CUSTOM_VAR').required().asString().validate(customValidator);
console.log(`Custom Var: ${customVar}`);
Other packages similar to env-var
dotenv
dotenv is a popular package for loading environment variables from a .env file into process.env. It does not provide validation or type conversion features like env-var, but it is widely used for managing environment variables in development.
joi
joi is a powerful schema description language and data validator for JavaScript. While it is not specifically designed for environment variables, it can be used to validate them. It offers more complex validation rules compared to env-var.
convict
convict is a configuration management tool for Node.js that allows you to define a schema for your configuration, including environment variables. It provides validation and default values, similar to env-var, but also supports nested configurations and different configuration sources.
env-var
Module that exposes a wrapper for process.env. You may wonder why, which is
pretty understandable. My primary reasoning for creating this module is to
assist in testing as explained below.
API
The API is just a single function that's exposed, let's call it getEnv.
getEnv([varname, [default]])
You can call this function 3 different ways:
- Calling without arguments will return the process.env Object.
- Calling with varname will return that variable value or undefined.
- Calling with varname, and default will return the value for varname
set on process.env, or if the variable is not set default is returned.
Example
var getEnv = require('env-var');
process.env.SOME_VAR = 'test';
var call1 = getEnv();
var call2 = getEnv('SOME_VAR');
var call3 = getEnv('NOT_SOME_VAR');
var call4 = getEnv('NOT_SOME_VAR', 'not-test');
Good for Testing?
When testing code that relies on environment variables sometimes we need to
mock out/set the environment variables. Having calls to process.env strewn
throughout a test is and can get confusing.
It's better to do something like this:
var env = require('env-var');
exports.concat = function (envVarToGet) {
return envVarToGet
.concat(' ')
.concat(
env.get(envVarToGet)
);
};
var sinon = require('sinon');
var expect = require('chai').expect;
var proxyquire = require('proxyquire');
describe('module test', function () {
var envStub;
var mod;
beforeEach(function () {
envStub = sinon.stub();
mod = proxyquire('./concat', {
'env-var': envStub
});
});
describe('#concat', function () {
envStub.returns('WORLD');
expect(mod.concat('HELLO')).to.equal('HELLO WORLD');
expect(envStub.called).to.be.true;
expect(envStub.getCall(0).args[0]).to.equal('HELLO');
});
});