Skip to content

benedictjohannes/env-config-parse

Repository files navigation

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

About

validate env variables with a simple templating system to write .env.example for NodeJS/bun

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors