Load environment variables from .env files and ensure they are defined by validating against an example file. Unlike the standard dotenv package, dotenv-safe guarantees that all required environment variables are present at runtime, preventing application failures due to missing configuration.
npm install dotenv-safeconst { config, parse, MissingEnvVarsError } = require('dotenv-safe');For ES modules:
import { config, parse, MissingEnvVarsError } from 'dotenv-safe';const dotenvSafe = require('dotenv-safe');
// Load and validate environment variables
const result = dotenvSafe.config();
// With options
const result = dotenvSafe.config({
example: '.env.example',
allowEmptyValues: false,
path: '.env'
});Load environment variables from .env files and validate them against an example file to ensure all required variables are defined.
/**
* Load and validate environment variables from .env files
* @param {Object} options - Configuration options
* @param {string} [options.path='.env'] - Path to .env file
* @param {string} [options.example='.env.example'] - Path to example file
* @param {string} [options.sample] - Alias for example option
* @param {boolean} [options.allowEmptyValues=false] - Allow empty environment variables
* @param {string} [options.encoding='utf8'] - Encoding for file reading
* @param {boolean} [options.debug=false] - Enable debug output
* @returns {Object} Result object with parsed and required variables
* @throws {MissingEnvVarsError} When required variables are missing
*/
function config(options = {});The returned object has the following structure:
{
parsed: {}, // Key-value pairs from .env file (empty if error occurred)
required: {}, // Key-value pairs required by example file and defined in environment
error?: Error // Error from dotenv if .env file could not be read
}Usage Examples:
// Basic usage
require('dotenv-safe').config();
// Custom example file for CI environments
require('dotenv-safe').config({
example: process.env.CI ? '.env.ci.example' : '.env.example'
});
// Allow empty values
require('dotenv-safe').config({
allowEmptyValues: true
});
// Custom paths
require('dotenv-safe').config({
path: './config/.env',
example: './config/.env.example'
});Parse environment file contents into a JavaScript object without loading into process.env.
/**
* Parse environment file contents into object
* @param {string|Buffer} src - Contents of environment file
* @returns {Object} Parsed key-value pairs
*/
function parse(src);Use the preloader to configure dotenv-safe from command line arguments and environment variables.
# Using Node.js require flag
node -r dotenv-safe/config your-script.js
# With environment variables
DOTENV_CONFIG_EXAMPLE=.env.production.example node -r dotenv-safe/config app.js
# With command line arguments
node -r dotenv-safe/config --dotenv_config_example=.env.prod app.jsThe preloader supports:
DOTENV_CONFIG_EXAMPLE environment variable for example file pathDOTENV_CONFIG_ALLOW_EMPTY_VALUES environment variable (allowEmptyValues defaults to true unless explicitly set to 'false')dotenv_config_<key>=<value> (parsed from process.argv)Custom error class thrown when required environment variables are missing from the environment.
/**
* Error thrown when required environment variables are missing
* @param {boolean} allowEmptyValues - Whether empty values are allowed
* @param {string} dotenvFilename - Path to .env file
* @param {string} exampleFilename - Path to example file
* @param {string[]} missingVars - Array of missing variable names
* @param {Error} [error] - Original dotenv error if any
*/
function MissingEnvVarsError(allowEmptyValues, dotenvFilename, exampleFilename, missingVars, error);
// Inherits from Error via util.inherits(MissingEnvVarsError, Error)
// Instance properties:
MissingEnvVarsError.prototype.name = 'MissingEnvVarsError';
MissingEnvVarsError.prototype.missing = []; // Array of missing variable names
MissingEnvVarsError.prototype.example = ''; // Path to example file
MissingEnvVarsError.prototype.sample = ''; // Alias for example property
MissingEnvVarsError.prototype.message = ''; // Detailed error messageUsage Example:
try {
require('dotenv-safe').config();
} catch (error) {
if (error instanceof MissingEnvVarsError) {
console.error('Missing variables:', error.missing);
console.error('Example file:', error.example);
}
throw error;
}All dotenv options are supported, plus additional validation-specific options:
| Option | Type | Default | Description |
|---|---|---|---|
path | string | .env | Path to environment file |
example | string | .env.example | Path to example file |
sample | string | - | Alias for example |
allowEmptyValues | boolean | false | Allow empty environment variables |
encoding | string | utf8 | File encoding |
debug | boolean | false | Enable debug output |
/**
* @typedef {Object} ConfigOptions
* @property {string} [path] - Path to .env file
* @property {string} [example] - Path to example file
* @property {string} [sample] - Alias for example
* @property {boolean} [allowEmptyValues] - Allow empty environment variables
* @property {string} [encoding] - File encoding
* @property {boolean} [debug] - Enable debug output
*/
/**
* @typedef {Object} ConfigResult
* @property {Object.<string, string>} parsed - Key-value pairs from .env file
* @property {Object.<string, string>} required - Key-value pairs required by example file
* @property {Error} [error] - Error from dotenv if .env file could not be read
*/