npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

env-var-provider

v2.3.0

Published

env-var-provider is a library that get environment variables.

Readme

env-var-provider

npm version license A TypeScript library for reading and validating environment variables with type safety and comprehensive validation rules.

Features

  • 🔒 Type-safe: Full TypeScript support with type definitions
  • Validation: Built-in validation rules (min, max, enum, regex, length, custom functions)
  • 🎯 Multiple types: Support for int, bool, str, json, array, and more
  • 🔄 DI friendly: Provider class for dependency injection frameworks
  • 📄 Documentation: Export environment variable documentation as Markdown or ConfigMap
  • 🧪 Well tested: Comprehensive test coverage

Installation

npm install env-var-provider

Quick Start

import { str, int, bool, array, strs, ints, json } from 'env-var-provider';

// Simple string
const apiUrl = str('API_URL', { defaultValue: 'http://localhost:3000' });

// Integer with validation
const port = int('PORT', { 
  defaultValue: 3000,
  min: 1,
  max: 65535
});

// Boolean
const isProduction = bool('IS_PRODUCTION', { defaultValue: false });

// JSON object
const config = json('CONFIG', { 
  defaultValue: { timeout: 5000 } 
});

// Array from indexed env vars (KEY_0, KEY_1, KEY_2...)
const hosts = array('HOST');

// Comma-separated strings
const allowedOrigins = strs('ALLOWED_ORIGINS');

// Comma-separated integers
const allowedPorts = ints('ALLOWED_PORTS');

API Reference

Reader Functions

str(key: string, config?: EnvConfig<string>): string

Read a string environment variable.

const name = str('APP_NAME', { 
  defaultValue: 'MyApp',
  isRequired: true,
  minLength: 3,
  maxLength: 50,
  regexp: /^[a-zA-Z0-9-]+$/
});

int(key: string, config?: EnvConfig<number>): number

Read an integer environment variable.

const timeout = int('TIMEOUT', {
  defaultValue: 3000,
  min: 1000,
  max: 10000,
  enum: [1000, 3000, 5000]
});

bool(key: string, config?: EnvConfig<boolean>): boolean

Read a boolean environment variable.

Accepts: true, false, 1, 0, yes, no, y, n, on, off, t, f, v, o (case-insensitive)

const debug = bool('DEBUG', { defaultValue: false });

json(key: string, config?: EnvConfig): any

Read and parse a JSON environment variable.

const config = json('CONFIG', {
  defaultValue: { retries: 3, timeout: 5000 }
});

strs(key: string, config?: EnvConfig<string[]>): string[]

Read a comma-separated list of strings. Also supports JSON array format.

// From: ORIGINS=http://localhost,https://example.com
// Or: ORIGINS=["http://localhost","https://example.com"]
const origins = strs('ORIGINS', {
  defaultValue: ['http://localhost'],
  minLength: 1,
  maxLength: 10
});

ints(key: string, config?: EnvConfig<number[]>): number[]

Read a comma-separated list of integers. Invalid numbers are filtered out.

// From: PORTS=3000,8080,9000
const ports = ints('PORTS', {
  defaultValue: [3000],
  min: 1,
  max: 65535
});

array(key: string, config?: EnvConfig<string[]>): string[]

Read an array from indexed environment variables.

// From: HOST_0=localhost, HOST_1=db.example.com, HOST_2=cache.example.com
const hosts = array('HOST', {
  defaultValue: ['localhost']
});
// Returns: ['localhost', 'db.example.com', 'cache.example.com']

Configuration Options

interface EnvConfig<T = any> {
  defaultValue?: T;           // Default value if not set
  description?: string;        // Description for documentation
  isRequired?: boolean;        // Throw error if not set
  
  // Validation rules
  min?: number;               // Min value (int, ints)
  max?: number;               // Max value (int, ints)
  minLength?: number;         // Min length (str, strs, ints, array)
  maxLength?: number;         // Max length (str, strs, ints, array)
  enum?: (string | number)[]; // Allowed values
  regexp?: RegExp;            // Pattern validation (str, strs)
  verifyFunction?: (value: T) => boolean; // Custom validation
  disabledTrim?: boolean;     // Don't trim string values
}

Provider Class (Dependency Injection)

Use with NestJS or other DI frameworks:

import { Provider } from 'env-var-provider';

const providers = [
  Provider.str('DATABASE_URL', { 
    isRequired: true 
  }),
  Provider.int('PORT', { 
    defaultValue: 3000 
  }),
  Provider.bool('ENABLE_CACHE', { 
    defaultValue: true 
  }),
  Provider.json('APP_CONFIG', { 
    defaultValue: {} 
  }),
  Provider.strs('ALLOWED_HOSTS'),
  Provider.ints('ALLOWED_PORTS'),
  Provider.array('SERVICES'),
];

// In NestJS module:
@Module({
  providers: providers,
  exports: providers,
})
export class ConfigModule {}

Export Documentation

Export as Markdown

import { exportMarkdown } from 'env-var-provider';

// After defining all your environment variables
exportMarkdown('./docs/environment-variables.md');

Generates a comprehensive Markdown table with all environment variables, their types, validation rules, and descriptions.

Export as Kubernetes ConfigMap

import { exportConfigMap } from 'env-var-provider';

exportConfigMap(
  './config-map.yml',
  'my-app-config',      // ConfigMap name
  'production',         // Namespace
  'v1'                  // API version (optional)
);

Generates a Kubernetes ConfigMap YAML with all defined environment variables and their default values.

Validation Examples

Required Field

const apiKey = str('API_KEY', { 
  isRequired: true 
});
// Throws error if API_KEY is not set

Numeric Range

const retries = int('RETRY_COUNT', {
  defaultValue: 3,
  min: 1,
  max: 10
});

String Pattern

const email = str('ADMIN_EMAIL', {
  regexp: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
  isRequired: true
});

Enum Values

const logLevel = str('LOG_LEVEL', {
  defaultValue: 'info',
  enum: ['debug', 'info', 'warn', 'error']
});

Custom Validation

const port = int('PORT', {
  defaultValue: 3000,
  verifyFunction: (value) => {
    // Custom logic
    return value !== 8080; // Don't allow 8080
  }
});

Array Length

const admins = strs('ADMIN_EMAILS', {
  minLength: 1,
  maxLength: 5,
  regexp: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
});

Error Handling

All validation errors throw descriptive error messages:

// Error: Error Env#PORT "min: 1000" is invalid: 500
const port = int('PORT', { min: 1000 });

// Error: Error Env#API_KEY "isRequired" is invalid: 
const apiKey = str('API_KEY', { isRequired: true });

// Error: Error Env#LOG_LEVEL "enum: debug,info,warn,error" is invalid: trace
const logLevel = str('LOG_LEVEL', { enum: ['debug', 'info', 'warn', 'error'] });

Advanced Usage

Access ENV_CONFIGS Map

import { ENV_CONFIGS } from 'env-var-provider';

// Get all registered environment variables
const allConfigs = Array.from(ENV_CONFIGS.values());

// Iterate through configurations
for (const [key, config] of ENV_CONFIGS) {
  console.log(`${key}: ${config.type} - ${config.description}`);
}

Browser Support

The library attempts to read from process.env first, then falls back to window.env for browser environments.

// Works in both Node.js and browser
const apiUrl = str('API_URL');

TypeScript Support

Full TypeScript support with proper type inference:

const port: number = int('PORT');
const enabled: boolean = bool('ENABLED');
const hosts: string[] = strs('HOSTS');
const config: any = json('CONFIG');

Testing

# Run tests
npm test

# Run tests with coverage
npm run coverage

Build

npm run build

License

MIT

Author

EJay Cheng

Repository

https://github.com/EJayCheng/env-provider