CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-dotenv-safe

Load environment variables from .env and ensure they are defined

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

index.mddocs/

dotenv-safe

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.

Package Information

  • Package Name: dotenv-safe
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install dotenv-safe

Core Imports

const { config, parse, MissingEnvVarsError } = require('dotenv-safe');

For ES modules:

import { config, parse, MissingEnvVarsError } from 'dotenv-safe';

Basic Usage

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'
});

Capabilities

Environment Variable Loading and Validation

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'
});

Environment File Parsing

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);

CLI Preloading

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.js

The preloader supports:

  • DOTENV_CONFIG_EXAMPLE environment variable for example file path
  • DOTENV_CONFIG_ALLOW_EMPTY_VALUES environment variable (allowEmptyValues defaults to true unless explicitly set to 'false')
  • Command line arguments in format dotenv_config_<key>=<value> (parsed from process.argv)

Error Handling

MissingEnvVarsError

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 message

Usage 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;
}

Configuration Options

All dotenv options are supported, plus additional validation-specific options:

OptionTypeDefaultDescription
pathstring.envPath to environment file
examplestring.env.examplePath to example file
samplestring-Alias for example
allowEmptyValuesbooleanfalseAllow empty environment variables
encodingstringutf8File encoding
debugbooleanfalseEnable debug output

Types

/**
 * @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
 */

Workflow

  1. Load .env file: Uses dotenv to load variables from specified .env file
  2. Read example file: Parses the example file to determine required variables
  3. Validate environment: Checks that all required variables exist in process.env
  4. Handle empty values: Optionally allows or rejects empty string values
  5. Throw on missing: Throws MissingEnvVarsError with detailed information if validation fails
  6. Return result: Returns object with parsed .env data and required variables from environment

Install with Tessl CLI

npx tessl i tessl/npm-dotenv-safe

docs

index.md

tile.json