safest-env
v0.0.1
Published
A tiny library for precise checking environment variables
Maintainers
Readme
safest-env
A tiny TypeScript library for precise validation of environment variables using Zod.
Lightweight, typed helper to validate process.env values at application startup and to convert/coerce common types (numbers, integers, booleans, URLs, emails, enums, etc.).
Repository: github.com/mirasayon/safest-env
NPM package: www.npmjs.com/package/safest-env
Why
- Avoid runtime crashes due to missing or malformed environment variables.
- Keep validation logic in a single place and get typed
envvalues for the rest of your app. - Built on top of Zod so you can combine built-in validators with custom Zod schemas.
Install
npm install safest-envQuick example
import { validateEnvironment, builtInSchemas as v } from "safest-env";
const env = validateEnvironment({
NODE_ENV: v.enum(["development", "test", "production"] as const),
PORT: v.integer(),
DEBUG: v.stringbool().optional(),
});
// `env` is typed: env.PORT is number, env.NODE_ENV is 'development' | 'production', etc.
console.log("Port: ", env.PORT);API
validateEnvironment(config)
Validate process.env against a record of Zod schemas.
- Input:
{ [ENV_NAME]: ZodSchema } - Output: typed record
{ [ENV_NAME]: ParsedValue }or throws:NoRequiredEnvVariableError— if a required env var is missing or empty.InvalidEnvVariableTypeError— if a value fails validation; error containscauseand messages from Zod.
Notes:
- This package is ESM-only and ships types
- If a schema accepts
undefined(e.g..optional()), the variable is considered optional. - The function uses
schema.safeParse(process.env[ENV_NAME])so it will coerce when you pass coercion schemas such asz.coerce.number().
builtInSchemas
A small helper collection returning common Zod schemas:
.string()—z.string().email()—z.string().email().url()—z.string().url().number()—z.coerce.number().integer()—z.coerce.number().int().stringbool(opts?)— string -> boolean coercion using common truthy/falsy values (configurable).enum([...])—z.enum([...])
Errors
The library throws two custom error classes to help you catch and log problems early:
NoRequiredEnvVariableError— thrown when a non-optional env var is missing or the value is an empty string.InvalidEnvVariableTypeError— thrown when a value fails schema validation. The error message contains Zod'streeifyError(...).errorslist.
License
MIT
