@usman-dev-studio/env-safe
v1.0.4
Published
Runtime env validation with full TypeScript inference. Zero dependencies.
Maintainers
Readme
env-safe
Runtime environment variable validation with full TypeScript inference. No Zod. No framework lock-in. Zero dependencies.
Installation
npm install @usman-dev-studio/env-safeQuick start
import { createEnv } from '@usman-dev-studio/env-safe'
const env = createEnv({
PORT: { type: 'port', default: 3000 },
DATABASE_URL: { type: 'url', protocols: ['postgres:'] },
NODE_ENV: { type: 'enum', values: ['development', 'production', 'test'] as const },
DEBUG: { type: 'boolean', default: false },
})
env.PORT // number
env.DATABASE_URL // string
env.NODE_ENV // 'development' | 'production' | 'test'
env.DEBUG // booleanField types
| Type | Output | Extra options |
|---|---|---|
| string | string | minLength, maxLength, pattern |
| number | number | min, max |
| boolean | boolean | — |
| url | string | protocols |
| email | string | — |
| port | number | — |
| enum | union literal | values (use as const) |
| json | T | — |
All fields support
| Option | Default | Description |
|---|---|---|
| required | true | false → returns undefined if absent |
| default | — | Used when variable is absent |
| description | — | Shown in error messages |
Error handling
All errors collected at once — not one at a time:
env-safe: environment validation failed:
✗ DATABASE_URL: is required — PostgreSQL connection string
✗ PORT: must be an integer between 1 and 65535 (got "abc")
✗ NODE_ENV: must be one of ["development", "production", "test"] (got "prod")Options
createEnv(schema, {
env?: Record<string, string | undefined> // default: process.env
onError?: 'throw' | 'warn' | 'silent' // default: 'throw'
reporter?: (message, errors) => void
logOnStart?: boolean
})License
MIT
