npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tsxo/envy

v0.6.1

Published

A lightweight, zero dependancy, and typesafe way to retrieve environment variables.

Readme

@tsxo/envy

A powerful, simple, and type-safe environment variable management library for Javascript and TypeScript applications.

CI License: MIT TypeScript npm Tree Shakeable Dotenv Compatible

Features

  • Type Safety - Full TypeScript support with comprehensive type definitions.
  • Value Transformation - Transform and normalize values with ease.
  • Validation - Rich set of built-in assertions for common use cases.
  • Type Conversion - Convert strings to numbers, booleans, arrays, and more.
  • Type Narrowing - Narrow types for more precise type safety.
  • Prefixed Variables - Group and namespace environment variables with automatic prefixing.
  • Method Chaining - Fluent API for building configurations.
  • Error Handling - Detailed error messages for missing or invalid values.
  • Dotenv Compatible - Fully compatible with Dotenv.
  • ESM and CJS - Seamlessly supports both ECMAScript Modules (ESM) and CommonJS (CJS) for flexibility across modern and legacy projects.
  • Tree-Shaking Ready - Designed with tree-shaking in mind to optimize application size.
  • Enhanced Dev Experience - Ships with TypeScript source for easier debugging during development.

Installation

npm install @tsxo/envy

Quick Start

All environment variable configurations in Envy follow a builder pattern, where you chain methods to assert, convert, and transfrom. Finally, you call .build() to get the final value. Each assertion, conversion, and transformation occur greedily (at the point they are called).

If you wish to use Dotenv, please import and configure it before using Envy.

import { envy, strConv, assert } from "@tsxo/envy";

// Required values.
// Required will trim the string and assert a minimum length of one.
const apiKey = envy.required("API_KEY").assert(assert.minLen(32)).build();

// Optional values with defaults.
// Required will trim the string and assert a minimum length of one.
const region = envy
    .optional("AWS_REGION", "us-east-1")
    .assert(assert.prefix("us-"))
    .build();

// Number conversion.
const port = envy.number("PORT", 3000).assert(assert.isPort()).build();

// Boolean conversion.
// Recognises the following values as `true`: "true", "yes", "1", "on".
// Recognises the following values as `false`: "false", "no", "0", "off".
const debug = envy.bool("DEBUG", false).build();

// Array parsing (comma-separated by default).
const whitelist = envy
    .array("IP_WHITELIST", ["127.0.0.1"])
    .assert(assert.minLen(1))
    .build();

// Manual conversion, transformation, and validation.
const manual = envy
    .optional("MANUAL", "42")
    .transform(s => s.trim())
    .assert(s => s.length() > 0, "Must have a length greater than zero")
    .convert(strConv.toNumber()) // You can use whichever method of conversion here.
    .build();

// Type narrowing.
type Region = "us-east-1" | "us-west-2";

function isRegion(val: string): val is Region {
    return val === "us-east-1" || val === "us-west-2";
}

const region = envy
    .required("AWS_REGION")
    .narrow(isRegion, "Invalid AWS region")
    .build(); // region is now typed as Region rather than string.

Core Concepts

Value Types

Envy supports several built-in types:

  • Strings - Default type for all environment variables
  • Numbers - Using strConv.toNumber or envy.number
  • Booleans - Using strConv.toBool or envy.bool
  • Arrays - Using strConv.toArray or envy.array

Type System

The library provides a robust type system for handling assertions, transformations, and error contexts.

Function Types

/**
 * Assertion function type that validates a value and provides metadata.
 */
type AssertFn<T> = {
    (v: T): boolean;
    context?: FnCtx;
};

/**
 * Function type for narrowing a value from type T to a more specific type N.
 */
type NarrowFn<T, N extends T> = (v: T) => v is N;

/**
 * Transform function for modifying values while maintaining their type.
 */
type TransformFn<T> = (v: T) => T;

/**
 * Conversion function for changing value types.
 */
type ConvertFn<In, Out> = (v: In) => Out;

Context Types

/**
 * Function metadata context for debugging and error handling.
 */
type FnCtx = {
    description: string;
    [key: string]: unknown;
};

/**
 * Error context with detailed information about failures.
 */
type ErrCtx = {
    description?: string;
    key?: string;
    value?: unknown;
    [key: string]: unknown;
};

Assertion System

Envy provides a comprehensive assertion system with built-in validators, the ability to create custom ones, or simply inline your logic.

Length Assertions

// Exact length.
const key = envy.required("API_KEY").assert(assert.len(32)).build();

// Minimum length.
const password = envy.required("DB_PASSWORD").assert(assert.minLen(8)).build();

// Maximum length.
const username = envy.required("DB_USER").assert(assert.maxLen(20)).build();

String Pattern Assertions

// Prefix validation.
const bucket = envy.required("S3_BUCKET").assert(assert.prefix("app-")).build();

// Suffix validation.
const logFile = envy.required("LOG_FILE").assert(assert.suffix(".log")).build();

// Substring check.
const dbUrl = envy
    .required("DATABASE_URL")
    .assert(assert.substring("postgres://"))
    .build();

// Regex matching.
const email = envy
    .required("ADMIN_EMAIL")
    .assert(assert.matches(/^admin-/)) // Ensure email starts with "admin-"
    .build();

URL and Network Assertions

// URL validation with protocol restrictions.
const apiEndpoint = envy
    .required("API_ENDPOINT")
    .assert(assert.isURL(["https:"]))
    .build();

// Port number validation.
const serverPort = envy.number("SERVER_PORT").assert(assert.isPort()).build();

Enumerated Values

// Restricted value set.
const logLevel = envy
    .required("LOG_LEVEL")
    .assert(assert.options(["debug", "info", "warn", "error"]))
    .build();

Creating Custom Assertions

Create reusable, type-safe assertions with rich error contexts:

// Custom port range validator.
const isServicePort = assert.create(
    (value: number) => value >= 1024 && value <= 49151,
    {
        description: "Must be a valid service port number",
        min: 1024,
        max: 49151,
    },
);

// Custom semantic version validator.
const isSemVer = assert.create(
    (value: string) => /^\d+\.\d+\.\d+$/.test(value),
    {
        description: "Must be a semantic version (x.y.z)",
        format: "semantic version",
        example: "1.0.0",
    },
);

// Usage
const servicePort = envy.number("SERVICE_PORT").assert(isServicePort()).build();

const version = envy.required("APP_VERSION").assert(isSemVer()).build();

Inline Assertions

While creating custom assertions is great for reusability, you can also write assertions inline using the assert method. This is particularly useful for one-off validations or simple checks:

// Simple inline assertion with custom error message
const username = envy
    .required("USERNAME")
    .assert(
        val => val.length >= 3 && val.length <= 20,
        "Username must be between 3 and 20 characters",
    )
    .build();

// Combining inline and custom assertions
const databaseUrl = envy
    .required("DATABASE_URL")
    .assert(assert.isURL(["postgres:"])) // Built-in assertion
    .assert(
        // Inline assertion
        url => url.includes("@") && url.includes("/"),
        "Database URL must include credentials and database name",
    )
    .build();

Prefixed Environment Variables

Envy supports automatic prefixing for better organization and namespacing of environment variables. This is especially useful for complex applications or microservices where you want to group related configuration.

import { envy, assert } from "@tsxo/envy";

// Create a prefixed builder.
const app = envy.withPrefix("APP");

// All variables will be prefixed with "APP_".
const port = app.number("PORT", 3000).assert(assert.isPort()).build(); // Reads APP_PORT
const debug = app.bool("DEBUG", false).build(); // Reads APP_DEBUG
const region = app.optional("AWS_REGION", "us-east-1").build(); // Reads APP_AWS_REGION

// Nested prefixes for hierarchical organization.
const db = app.withPrefix("DB");
const dbHost = db.required("HOST").build(); // Reads APP_DB_HOST
const dbPort = db.number("PORT", 5432).build(); // Reads APP_DB_PORT
const dbName = db.required("NAME").build(); // Reads APP_DB_NAME

Error Types

The library uses three specific error types:

  • MissingError

    • Thrown when a required environment variable is not found
    • Contains the missing variable key and a descriptive message
  • AssertError

    • Thrown when a validation check fails
    • Includes the failed value, assertion description, and any custom context
  • ConversionError

    • Thrown when type conversion fails (e.g., converting "abc" to a number)
    • Contains the original value, target type, and reason for failure

Best Practices

  1. Validation First: Add assertions immediately after defining variables
  2. Chain Assertions: Use multiple assertions to create robust validation
  3. Meaningful Messages: Provide clear error messages for assertions
  4. Type Safety: Use appropriate assertions with type conversions
  5. Documentation: Document expected formats and constraints

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT License - fork, modify and use however you want.