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

envsentry

v1.0.4

Published

Environment variable validation library with TypeScript support

Readme

EnvSentry

A powerful environment variable validation library with full TypeScript support. EnvSentry helps you validate, transform, and handle environment variables with ease, making your applications more robust and error-resistant.

Features

  • 🛡️ Type Safety - Full TypeScript support with type inference
  • Powerful Validators - Validate strings, numbers, URLs, emails, and more
  • 🔄 Dotenv Integration - Seamless integration with .env files
  • ⚙️ Customizable Rules - Create complex validation rules for your environment
  • 🚫 Error Handling - Clear error messages when validation fails
  • 📊 Detailed Reporting - Generate comprehensive reports on your environment setup
  • 🏭 Environment Templates - Generate example .env files from your schema

Installation

To install the package, run:

With npm

npm install envsentry

With yarn

yarn add envsentry

With pnpm

pnpm install envsentry

With bun

bun add envsentry

Quick Start

import { cleanEnv, str, num, bool, url } from "envsentry";

// Define and validate your environment
const env = cleanEnv({
  NODE_ENV: str({ choices: ["development", "production", "test"] }),
  PORT: num({ default: 3000 }),
  DEBUG: bool({ default: false }),
  API_KEY: str({ required: true }),
  API_URL: url({ protocols: ["https"] }),
});

// Use your validated environment variables with full type safety
console.log(`Server running on port ${env.PORT}`);
console.log(`Environment: ${env.NODE_ENV}`);

Available Validators

envsentry comes with a rich set of validators to match your needs:

| Validator | Description | Options | | ------------ | -------------------- | --------------------------------------------------------------------- | | str() | String values | choices, default, minLength, maxLength, pattern, required | | num() | Numeric values | choices, default, min, max, integer, required | | bool() | Boolean values | default, required | | port() | TCP/UDP port numbers | default, required | | url() | URL values | default, protocols, required | | email() | Email addresses | default, required | | json() | JSON strings | default, required, schema | | date() | Date strings | default, required, min, max | | array() | Array values | default, separator, itemValidator, itemParser, required | | filePath() | File paths | default, mustExist, canBeDir, required | | host() | Hostnames | default, required |

Advanced Usage

Validator Options

interface ValidatorSpec<T> {
  /**
   * The type of validator (string, number, boolean, etc.)
   */
  type: string;

  /**
   * The validation function that checks the value
   */
  validator: (value: any) => boolean;

  /**
   * Optional default value
   */
  default?: T;

  /**
   * Optional list of allowed values
   */
  choices?: T[];

  /**
   * Function to parse string value to the expected type
   */
  parse?: (value: string) => T;

  /**
   * Error message to show when validation fails
   */
  message?: string;

  /**
   * Whether the value is required
   */
  required?: boolean;
}

Comprehensive Validation

envsentry allows you to define comprehensive validation rules for your environment variables:

import { cleanEnv, str, num, bool, url, email, port, json } from "envsentry";

const env = cleanEnv({
  // Server configuration
  NODE_ENV: str({
    choices: ["development", "production", "test"],
    default: "development",
  }),
  PORT: port({ default: 3000 }),

  // API Configuration
  API_URL: url({
    protocols: ["https"],
    message: "API URL must be a valid HTTPS URL",
  }),

  // Database configuration
  DB_CONNECTION: str({
    pattern: /^mongodb(\+srv)?:\/\/.+$/,
    message: "Must be a valid MongoDB connection string",
  }),

  // User-related settings
  ADMIN_EMAIL: email({ required: true }),
  USER_LIMITS: json({
    default: { maxUploads: 5, maxProjects: 10 },
    schema: (data) =>
      typeof data === "object" &&
      typeof data.maxUploads === "number" &&
      typeof data.maxProjects === "number",
  }),

  // Feature flags
  ENABLE_FEATURE_X: bool({ default: false }),
});

Dotenv Configuration

envsentry integrates with dotenv to load environment variables from a file:

const env = cleanEnv(
  {
    NODE_ENV: str({ choices: ["development", "production", "test"] }),
    PORT: num({ default: 3000 }),
  },
  {
    dotenv: {
      path: ".env.production",
      override: true,
      optional: true,
    },
  }
);

Generate Example Environment File

Create a template .env file based on your schema:

import { generateEnvFile, str, num, bool, url } from "envsentry";

generateEnvFile(
  {
    NODE_ENV: str({ choices: ["development", "production", "test"] }),
    PORT: num({ default: 3000 }),
    API_KEY: str({ required: true }),
    DEBUG: bool({ default: false }),
    API_URL: url(),
  },
  ".env.example"
);

Environment Reporting

Get comprehensive reports about your environment variables:

import { printEnvStatus, str, num, bool } from "envsentry";

// Print a detailed report of environment variables
printEnvStatus({
  NODE_ENV: str({ choices: ["development", "production", "test"] }),
  PORT: num({ default: 3000 }),
  DEBUG: bool({ default: false }),
});

Usage with Express

import express from "express";
import { cleanEnv, str, port, bool } from "envsentry";

// Validate environment
const env = cleanEnv({
  PORT: port({ default: 3000 }),
  NODE_ENV: str({ choices: ["development", "production", "test"] }),
  ENABLE_CORS: bool({ default: true }),
});

const app = express();

// Use validated environment
if (env.ENABLE_CORS) {
  app.use(cors());
}

app.listen(env.PORT, () => {
  console.log(`Server running on port ${env.PORT} in ${env.NODE_ENV} mode`);
});

API Reference

Main Functions

| Function | Description | | ------------------- | --------------------------------------------------------- | | cleanEnv() | Validates environment variables against a schema | | testEnv() | Tests if environment variables are valid without throwing | | reportEnv() | Generates a detailed report about environment variables | | printEnvStatus() | Prints environment status to the console | | generateEnvFile() | Creates an example .env file from schema | | loadEnvFile() | Loads environment variables from a file | | mergeEnv() | Merges custom environment variables with process.env |

Options

interface EnvValidatorOptions {
  /**
   * Dotenv options
   */
  dotenv?: {
    path?: string; // Path to .env file
    silent?: boolean; // Suppress errors
    override?: boolean; // Override existing env vars
    optional?: boolean; // Don't fail if file not found
  };

  /**
   * Only allow variables defined in schema
   */
  strict?: boolean;

  /**
   * Show warnings and info
   */
  verbose?: boolean;

  /**
   * Throw on validation errors
   */
  throwOnError?: boolean;
}

Example .env

# Server Configuration
NODE_ENV=development
PORT=3000
HOST=localhost

# API Configuration
API_URL=https://api.example.com
API_KEY=your-secret-key

# Database Configuration
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=password
DB_NAME=mydatabase

# Feature Flags
ENABLE_FEATURE_X=true
DEBUG=false

TypeScript Support

envsentry is built with TypeScript and provides excellent type inference:

import { cleanEnv, str, num } from "envsentry";

const env = cleanEnv({
  PORT: num(),
  NODE_ENV: str(),
});

// TypeScript knows the types!
const port: number = env.PORT; // ✓
const mode: string = env.NODE_ENV; // ✓

// These would cause compile errors:
// const port: string = env.PORT;   // ✗ Type 'number' is not assignable to type 'string'
// const foo = env.FOO;             // ✗ Property 'FOO' does not exist

Contribute

We welcome contributions! Feel free to open an issue or submit a pull request.

For more details, visit the GitHub repository.

License

This project is licensed under the MIT License