Skip to content

Shoon23/zenvx

Repository files navigation

zenvx

Type-safe environment variables with Zen-like peace of mind.

zenvx is a lightweight wrapper around Zod and dotenv designed to fix the common headaches of environment variables in Node.js / TypeScript. It provides strict validation (blocking "123" as an API Key), smart coercion, and beautiful, human-readable error reporting.

License TypeScript NPM


Why zenvx?

Standard Zod is great, but environment variables are always strings. This leads to common pitfalls:

  • z.string() accepts "12345", which is usually a mistake for API keys
  • z.boolean() fails on "true" strings
  • Validation errors are often ugly JSON dumps that clog your terminal

zenvx solves this:

  1. Strict Validatorstx.string() ensures values are text, not just numbers
  2. Smart Coercion – Automatically handles ports, numbers, and booleans
  3. Beautiful Errors – Formatting that tells you exactly what to fix

Features

  • ✅ Type-safe environment variables
  • ✅ Smart coercion for numbers, booleans, and ports
  • ✅ Strict validation for strings, URLs, emails, JSON, enums
  • ✅ Beautiful, human-readable error reporting
  • ✅ Seamless TypeScript integration
  • .env.example auto-generation
  • ✅ Runtime and build-time validation modes
  • ✅ Framework adapters: Node.js, Next.js (server + client), Vite

Installation

npm install zenvx zod
# or
pnpm add zenvx zod
# or
yarn add zenvx zod

Note: Zod is a peer dependency, so you must have it installed.

Quick Start

Create a file (e.g., src/env.ts) and export your configuration:

import { defineEnv, tx } from "zenvx";

export const env = defineEnv({
  // 1. Smart Coercion
  PORT: tx.port(), // Coerces "3000" -> 3000
  DEBUG: tx.bool(), // Coerces "true"/"1" -> true

  // 2. Strict Validation
  DATABASE_URL: tx.url(), // Must be a valid URL
  API_KEY: tx.string(), // "12345" will FAIL (Must be text)

  // 3. Native Zod Support (optional)
  NODE_ENV: tx.enum(["development", "production"]),
});

Now use it anywhere in your app:

import { env } from "./env";

console.log(`Server running on port ${env.PORT}`);
// TypeScript knows env.PORT is a number!

Framework Adapters

zenvx supports different frameworks with adapters for proper environment handling.

Node.js

import { loadNodeEnv } from "zenvx/node";

const env = loadNodeEnv({
  PORT: tx.port(),
  DEBUG: tx.bool(),
});

Note: In Node.js, you must install dotenv separately and load it (e.g., via import "dotenv/config" or dotenv.config()) before calling loadNodeEnv().

Next.js

Server-side

import { loadServerEnv } from "zenvx/next";

const env = loadServerEnv({
  PORT: tx.port(),
  SECRET_KEY: tx.string(),
});

Client-side (only NEXTPUBLIC* allowed):

import { loadClientEnv } from "zenvx/next";

const env = loadClientEnv({
  NEXT_PUBLIC_API_URL: tx.string(),
  NEXT_PUBLIC_DEBUG: tx.bool(),
});

Attempting to access a key without NEXTPUBLIC in client env throws an error.

Vite

import { loadViteEnv } from "zenvx/vite";

const env = loadViteEnv({
  VITE_API_URL: tx.string(),
  VITE_DEBUG: tx.bool(),
});

.env.example Auto-Generation

zenvx can automatically generate a .env.example file from your schema — keeping your documentation always in sync.

defineEnv(
  {
    DATABASE_URL: tx.url(),
    PORT: tx.port().default(3000),
    DEBUG: tx.bool(),
  },
  {
    generateExample: true,
  },
);

This produces:

# Example environment variables
# Copy this file to .env and fill in the values

DATABASE_URL=  #string
PORT=3000  # number
DEBUG_MODE=  # boolean

No more forgotten or outdated .env.example files.

Runtime vs Build-Time Validation

Different environments need different failure behavior. zenvx supports both.

Runtime Validation (default)

In runtime mode, environment variables are validated as soon as your application starts.

defineEnv(schema, { mode: "runtime" });

Behavior:

  • Environment variables are loaded and validated immediately
  • If validation fails:
    • A formatted error message is printed to the console
    • The process exits using process.exit(1)
  • Prevents the application from running with invalid configuration

This mode ensures misconfigured environments are caught early and stop execution entirely.

Build-Time Validation

IIn build-time mode, validation errors are thrown instead of terminating the process.

defineEnv(schema, { mode: "build" });

Behavior:

  • Environment variables are validated during execution
  • If validation fails:
    • An error is thrown
    • process.exit() is not called
  • Allows the calling environment (bundler, test runner, or script) to handle the failure

This mode avoids hard exits and lets external tooling decide how to respond to configuration errors.

Beautiful Error Handling

If your .env file is missing values or has invalid types, zenvx stops the process immediately and prints a clear message:

┌──────────────────────────────────────────────┐
│ ❌ INVALID ENVIRONMENT VARIABLES DETECTED │
└──────────────────────────────────────────────┘
PORT: Must be a valid port (1-65535)
API_KEY: Value should be text, but looks like a number.
DATABASE_URL: Must be a valid URL

The tx Validator Helper

zenvx provides a tx object with pre-configured Zod schemas optimized for .env files.

Validator Description Example Input (.env) Result (JS)
tx.string() Strict string. Rejects purely numeric values (prevents lazy keys). abc_key "abc_key"
tx.number() Coerces string to number. "50" 50
tx.bool() Smart boolean. Accepts true, false, 1, 0. "true", "1" true
tx.port() Validates port range (1-65535). "3000" 3000
tx.url() Strict URL validation. "https://site.com" "https://..."
tx.email() Valid email address. "admin@app.com" "admin@..."
tx.json() Parses a JSON string into an Object. {"foo":"bar"} {foo: "bar"}
tx.enum([...]) Strict allow-list. "PROD" "PROD"

Customizing Error Messages

Every tx validator accepts an optional custom error message.

export const env = defineEnv({
  API_KEY: tx.string("Please provide a REAL API Key, not just numbers!"),
  PORT: tx.port("Port is invalid or out of range"),
});

Mixing with Standard Zod

You can mix tx helpers with standard Zod schemas if you need specific logic.

import { defineEnv, tx } from "zenvx";
import { z } from "zod";

export const env = defineEnv({
  PORT: tx.port(),

  // Standard Zod Schema
  APP_NAME: z.string().min(5).default("My Super App"),
});

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors