Environment variable configuration for Node.js made easy.
npm install @strattadb/environment




Environment variable configuration for Node.js made easy.
A lot of applications need to ensure that some environment variables are
set from the beginning, and checking if the value in process.env is undefined
every time is needed gets tedious very fast.
environment allows applications to ensure required env variables are set and are valid according
to _your_ definition of valid. See how to use it.
- environment
- The problem
- Table of Contents
- Installation
- Usage
- Examples
- API
- [makeEnv(schema: Schema, processEnv?: { [key: string]: string | undefined }): Env](#makeenvschema-schema-processenv--key-string-string--undefined--env)
- Parsers
- parsers.string(value: string): string
- parsers.boolean(value: string): boolean
- parsers.integer(value: string): number
- parsers.float(value: string): number
- parsers.email(value: string): string
- parsers.url(value: string): string
- parsers.ipAddress(value: string): string
- parsers.port(value: string): number
- [parsers.whitelist(whitelistedValues: string[]): Parser](#parserswhitelistwhitelistedvalues-string-parserstring)
- parsers.regex(pattern: Regex): Parser
- parsers.array
- parsers.positiveInteger(value: string): number
- parsers.nonPositiveInteger(value: string): number
- parsers.negativeInteger(value: string): number
- parsers.nonNegativeInteger(value: string): number
- Recipes
- Making environment variables required
- Specifying a default value for when the env variable is not required
- Providing a custom parser
- Usage with Dotenv
- Providing your own processEnv object
- FAQ
- Where should I call makeEnv in my application?
- Does it support changing env variables dynamically?
- Can I use the debug module with environment?
- Can I have more than one env object per application?
- Node.js support
- Contributing
- Maintainers
- Who's using environment
- Related libraries
- License
With Yarn:
``bash`
yarn add @strattadb/environment
or with npm:
`bash`
npm install @strattadb/environment
An example env.js file:
`javascript
// env.js
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv({
nodeEnv: {
parser: parsers.whitelist(['production', 'development', 'test']),
required: true,
envVarName: 'NODE_ENV',
},
port: {
parser: parsers.port,
required: false,
defaultValue: 4000,
envVarName: 'PORT',
},
});
export default env;
`
Now in a file:
`javascript
// otherFile.js
import env from './env';
console.log(env.nodeEnv); // development
console.log(typeof env.nodeEnv); // string
console.log(env.port); // 4000
console.log(typeof env.port); // number
`
Ensures required env variables are present and returns an env object.
Supports passing a processEnv object as the second argument.
If it's not passed, it uses process.env.
This object will be used to look up the environment variables.
- Schema:
- \[key: string\]: object - The key will be accessiblefunction
in the returning env object.
- parser: - A function that takes a string and can return anything.env[key]
The return value will be accesible in .boolean
If the argument is not valid, it should throw.
- required: - Whether or not the env variable is required.true
If the value and the env variable is not set, it'll throw.false
If the value is it'll look for the env variable in process.env,defaultValue
if isn't set, it'll use .any?
- defaultValue: - Only valid if required: false.string
This is the default value of the env variable if it's not set.
It won't be parsed or validated.
- envVarName: - The name of the env variable to look upprocess.env[envVarName]
().string?
- description: - Helper text describing the variable.
- Env:
- \[key: string\]: any - The keys are the same as the ones in the schema.
#### parsers.string(value: string): string
Trivial parser. It doesn't do any validation.
#### parsers.boolean(value: string): boolean
Ensures the value is a truthy or falsy value.
Truthy values: 'true', '1', 'yes', 'on'.
Falsy values: 'false', '0', 'no', 'off'.
#### parsers.integer(value: string): number
Ensures the value is an integer.
#### parsers.float(value: string): number
Ensures the value is a float.
#### parsers.email(value: string): string
Ensures the value is an email.
#### parsers.url(value: string): string
Ensures the value is a url.
#### parsers.ipAddress(value: string): string
Ensures the value is an IP address.
#### parsers.port(value: string): number
Ensures the value is a port.
#### parsers.whitelist(whitelistedValues: string[]): Parser
Takes a list of valid values and returns a parser that
ensures the value is in the whitelist.
Example:
`javascript
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv({
color: {
parser: parsers.whitelilst(['red', 'blue', 'green']),
required: true,
envVarName: 'COLOR',
},
});
`
#### parsers.regex(pattern: Regex): Parser
Takes a regex and returns a parser that
ensures the value matches the pattern.
Example:
`javascript
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv({
color: {
parser: parsers.regex(/^green$/),
required: true,
envVarName: 'COLOR',
},
});
`
#### parsers.array
Takes a parser and returns a parser that parses a list of values.
The default value separator is ','.
Example:
`javascript
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv({
color: {
parser: parsers.array({ parser: parsers.integer }),
required: true,
envVarName: 'FAVORITE_NUMBERS',
},
});
`
#### parsers.positiveInteger(value: string): number
Ensures the value is a positive integer.
#### parsers.nonPositiveInteger(value: string): number
Ensures the value is a non-positive integer.
#### parsers.negativeInteger(value: string): number
Ensures the value is a negative integer.
#### parsers.nonNegativeInteger(value: string): number
Ensures the value is a non-negative integer.
If required is true and the environment variable isn't set,
it'll throw:
`javascript
// env.js
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv({
notSet: {
parser: parsers.string,
required: true,
envVarName: 'NOT_SET',
},
});
`
`bash
node env.js
EnvironmentVariableError: NOT_SET is required but is not set
at ...
...
`
If the env variable is not required you must specify a default value:
`javascript
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv({
port: {
parser: parsers.port,
required: false,
defaultValue: 4000,
envVarName: 'PORT',
},
});
console.log(env.port); // 4000
`
A parser function must take a string value and can return anything.
The value you return is what you'll get in the env object.
If the value is not valid you should throw an error:
`javascript
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv({
someValue: {
parser: (value) => {
if (value === 'forbiddenValue') {
throw new Error('value is forbidden');
}
return value;
},
required: true,
envVarName: 'SOME_VALUE',
},
});
`
A common pattern is to load the env variables from a file using dotenv
and then ensuring that the required variables are actually present:
`javascript
const dotenv = require('dotenv');
dotenv.config(); // Loads env variables from .env file to process.env.
const { makeEnv, parsers } = require('@strattadb/environment');
const env = makeEnv({
secretToken: {
parser: parsers.string,
required: true,
envVarName: 'SECRET_TOKEN',
},
});
`
By default, makeEnv uses process.env to look up and get environment variables,process.env
but you can pass you own processEnv object as the second argument that will
be used instead of :
`javascript
import { makeEnv, parsers } from '@strattadb/environment';
const env = makeEnv(
{
hello: {
parser: parsers.string,
required: true,
envVarName: 'HELLO',
},
},
{
HELLO: 'WORLD',
},
);
`
The best place to create the env object is very early
in your application startup.
Everything before you call makeEnv with your schema will
not be guaranteed to have your required env variables.
No, when you create an env object it will read the value of
process.env at that time. After that, if anything makesprocess.env
changes to , it will not be reflected in the
env object.
Yes! Set DEBUG=environment`.
Yes! You can have as many env objects as you want!
Node.js version 10 or higher. Every version of this library
is tested in Node.js 10, 12, 14 and 15.
PRs, feature requests, bug reports, and any kind of contributions are welcome!
See CONTRIBUTING.md.
- origen
- Convict
- Envalid
- require-environment-variables
- Dotenv