Schema-based environment variable validation with type-safe accessors
npm install @philiprehberger/env-validatorSchema-based environment variable validation with type-safe accessors
npm install @philiprehberger/env-validator
import { createEnv } from '@philiprehberger/env-validator';
const env = createEnv({
DATABASE_URL: { type: 'url', required: true },
PORT: { type: 'port', default: 3000 },
NODE_ENV: { type: 'enum', values: ['development', 'production', 'test'] },
ENABLE_CACHE: { type: 'boolean', default: false },
ADMIN_EMAIL: { type: 'email', required: true },
MAX_CONNECTIONS: { type: 'number', default: 10 },
FEATURE_FLAGS: { type: 'json', default: {} },
});
env.DATABASE_URL; // string (typed, validated)
env.PORT; // number
env.ENABLE_CACHE; // boolean
| Type | Parses to | Validation |
|---|---|---|
string | string | Any non-empty string |
number | number | Valid number |
boolean | boolean | true/false/1/0/yes/no |
url | string | Valid URL |
email | string | Valid email format |
enum | string | One of specified values |
port | number | Integer 0–65535 |
json | unknown | Valid JSON |
All validation errors are collected and reported at once:
// If DATABASE_URL and ADMIN_EMAIL are both missing:
// EnvValidationError: Environment validation failed:
// Missing required environment variable: DATABASE_URL
// Missing required environment variable: ADMIN_EMAIL
const env = createEnv(schema, {
DATABASE_URL: 'postgres://localhost/mydb',
PORT: '8080',
});
createEnv<S extends Schema>(schema: S, source?: Record<string, string | undefined>): InferEnv<S>Validates environment variables against the given schema and returns a type-safe object. Throws EnvValidationError if any validation fails. If source is omitted, reads from process.env.
SchemaA record mapping variable names to FieldConfig objects:
type Schema = Record<string, FieldConfig>;
FieldConfig| Property | Type | Description |
|---|---|---|
type | 'string' | 'number' | 'boolean' | 'url' | 'email' | 'enum' | 'port' | 'json' | Validation type. |
required | boolean | Whether the variable must be present. Default: false. |
default | Varies by type | Default value if missing. Makes the field effectively required in the output type. |
values | readonly string[] | (enum only) Allowed values. |
EnvValidationErrorThrown when one or more variables fail validation.
| Property | Type | Description |
|---|---|---|
message | string | Human-readable summary of all failures. |
errors | string[] | Array of individual error messages. |
InferEnv<S>TypeScript utility type that infers the output type from a schema. Required fields and fields with defaults are non-optional; others are optional.
npm install
npm run build
npm test
If you find this project useful: