env-config-parse
v0.2.0
Published
Robust and type-safe environment variable configuration parser
Maintainers
Readme
env-config-parse
Tired of manual
.env.examplemaintenance? This lib auto-generates it from your TS schema while validating at runtime.
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:
- Missing Keys: New developers pull the code, copy
.env.exampleto.env, and the app crashes because of missing keys. - Outdated Defaults: The example file contains stale or incorrect default values.
- No Validation: There's no guarantee that the values in your
.envactually 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:
- Runtime Validation: It parses and validates
process.envvalues at runtime, ensuring your app has valid config before it starts. - Template Generation: It can generate a fresh, up-to-date
.env.examplefile directly from your definition, including commented lines.
Installation
npm install env-config-parseIf you want to use the zValidator method for advanced schema validation:
npm install zodUsage
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). Usedotenv,process.loadEnvFile(Node 20+), or container environment variables before using this parser inenvmode.
// 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 fromprocess.envimmediately when you define the key. Useful for your runtime application config.schema: Ignoresprocess.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 toconsole.warnand falls back to thedefaultValue.'silent': Silently falls back to thedefaultValue.- Function: Pass a custom callback
(error: EnvConfigError) => voidto handle errors your way.
API Overview
string(key, default, validator?): Parses a string.number(key, default, validator?): Parses a number. HandlesNaNcheck.integer(key, default, validator?): Parses an integer.boolean(key, default): Parses booleans. Supportstrue,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.envfile content.
License
MIT
