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-config-parse

v0.2.0

Published

Robust and type-safe environment variable configuration parser

Readme

env-config-parse

Tired of manual .env.example maintenance? This lib auto-generates it from your TS schema while validating at runtime.

npm version License: MIT

Rationale: The "Code Drift" Problem

In many projects, the .env.example (or example.env) file is maintained manually. As developers add new features and environment variables, they often forget to update the example file. This leads to Code Drift:

  1. Missing Keys: New developers pull the code, copy .env.example to .env, and the app crashes because of missing keys.
  2. Outdated Defaults: The example file contains stale or incorrect default values.
  3. No Validation: There's no guarantee that the values in your .env actually match what the application expects (types, formats, etc.).

env-config-parse solves this by making your CODE the source of truth.

You define your configuration schema in TypeScript/JavaScript. This schema serves two purposes:

  1. Runtime Validation: It parses and validates process.env values at runtime, ensuring your app has valid config before it starts.
  2. Template Generation: It can generate a fresh, up-to-date .env.example file directly from your definition, including commented lines.

Installation

npm install env-config-parse

If you want to use the zValidator method for advanced schema validation:

npm install zod

Usage

1. Define your Configuration

Create a file (e.g., src/config.ts) to define your environment variables.

Note: This library does not load environment variables from a file (like .env). Use dotenv, process.loadEnvFile (Node 20+), or container environment variables before using this parser in env mode.

// src/config.ts
import { EnvConfigParser } from 'env-config-parse'
import { z } from 'zod' // Optional, if using zValidator

// Initialize parser
// mode: 'env' -> reads from process.env immediately
// onValidationError: 'throw' -> stops app startup if config is invalid
const parser = new EnvConfigParser({ 
  mode: 'env', 
  onValidationError: 'throw' 
})

export const config = {
  // Add visual sections for your generated .env.example
  ...parser.section('==== App Config ===='),
  
  // Basic types
  NODE_ENV: parser.string('NODE_ENV', 'development'),
  PORT: parser.number('PORT', 3000),
  DEBUG: parser.boolean('DEBUG', false),

  ...parser.section('==== Database ===='),
  
  // Custom validation logic
  DB_HOST: parser.string('DB_HOST', 'localhost', (val) => {
    if (val === 'restricted-host') throw new Error('Cannot use this host')
    return val
  }),

  // Advanced validation with Zod (requires zod peer dependency)
  EMAIL_PROVIDER: parser.zValidator(
    'EMAIL_PROVIDER', 
    z.enum(['smtp', 'ses', 'sendgrid']), 
    'smtp'
  ),
  
  // Pass through sensitive values (validation logic is up to you)
  SECRET_KEY: parser.passThrough('SECRET_KEY'),
}

2. Generate .env.example

You can create a script to generate your template file. This ensures your documentation is always in sync with your code.

See example.config.ts for a full example.

// scripts/generate-env.ts
import fs from 'node:fs'
import path from 'node:path'
import { EnvConfigParser } from 'env-config-parse'

// Use 'schema' mode to define structure without validating/reading process.env
const parser = new EnvConfigParser({ mode: 'schema' })

// ... (Define your config schema here, or import a shared definition factory) ...

// Generate the string
const template = parser.getTemplateString()
fs.writeFileSync(path.resolve(__dirname, '../.env.example'), template)

See the example output: example.config.env

Key Concepts

It is NOT a .env Loader

env-config-parse assumes your environment variables are already populated in process.env.

  • Development: Use import 'dotenv/config' at the top of your entry file.
  • Production: Set environment variables via your platform (Docker, Kubernetes, Vercel, etc.).

Modes: env vs schema

  • env (Default): Reads values from process.env immediately when you define the key. Useful for your runtime application config.
  • schema: Ignores process.env. Returns the default value immediately. Used when you only want to define the structure to generate a template file, without failing due to missing keys in your local environment.

Error Handling (onValidationError)

  • 'throw': (Default) Throws an error immediately if a validation fails. Best for failing fast at startup.
  • 'warn': Logs a warning to console.warn and falls back to the defaultValue.
  • 'silent': Silently falls back to the defaultValue.
  • Function: Pass a custom callback (error: EnvConfigError) => void to handle errors your way.

API Overview

  • string(key, default, validator?): Parses a string.
  • number(key, default, validator?): Parses a number. Handles NaN check.
  • integer(key, default, validator?): Parses an integer.
  • boolean(key, default): Parses booleans. Supports true, 1, yes, on (case-insensitive).
  • zValidator(key, zodSchema, default): Uses a Zod schema for validation.
  • passThrough(key): value directly from env.
  • section(title): Adds a comment section to the generated template.
  • parseEnv(source?): Re-evaluates the entire schema against a new source object.
  • getTemplateString(): Returns the formatted .env file content.

License

MIT