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

env-safe-check

v1.2.1

Published

Validate environment variables with schema-based parsing, defaults, and clear runtime errors.

Downloads

980

Readme

env-safe-check

Zero-dependency, type-safe environment validation for Node.js & TypeScript

npm version npm downloads license node TypeScript


✨ What is env-safe-check?

env-safe-check is a lightweight, zero-dependency library that validates environment variables at application startup.

It ensures your app:

  • 🚨 Fails fast when required variables are missing
  • 🎯 Validates types (string, number, boolean, json)
  • 🧠 Supports custom validators with helpful hints
  • 🧩 Provides defaults for optional variables
  • 🎨 Outputs clean, CLI-friendly error messages
  • 🔒 Is CI-safe (non-zero exit on validation failure)

Stop debugging production issues caused by misconfigured environment variables.


🚀 Quick Start

Install

npm install env-safe-check
# or
yarn add env-safe-check
# or
pnpm add env-safe-check

⚡ TL;DR (Recommended Schema Mode)

import { validateEnv } from 'env-safe-check';

export const env = validateEnv({
  schema: {
    DATABASE_URL: {
      type: 'string',
      description: 'PostgreSQL connection URL',
    },

    PORT: {
      type: 'number',
      default: '3000',
    },

    DEBUG: {
      type: 'boolean',
      required: false,
      default: 'false',
    },

    NODE_ENV: {
      type: 'string',
      validator: (value) =>
        ['development', 'production', 'test'].includes(value)
          ? true
          : 'Must be one of: development, production, test',
      validatorHint: 'development | production | test',
    },

    FEATURE_FLAGS: {
      type: 'json',
      required: false,
    },
  },
});

console.log(env.PORT); // number

CLI Companion

You can run validation without importing the library in app code:

# with .env loading
npx env-safe-check validate --schema ./env.schema.js --env-file ./.env

This is useful for CI preflight checks and npm scripts:

{
  "scripts": {
    "validate:env": "env-safe-check validate --schema ./env.schema.js"
  }
}

CLI options

| Option | Description | |--------|-------------| | validate | Validate env variables using a schema module | | --schema <path> | Path to a module that exports schema (default, schema, or envSchema) | | --env-file <path> | Load env vars from file before validation | | --silent | Suppress non-error output |

Schema file example:

export default {
  DATABASE_URL: {
    type: "string",
    description: "PostgreSQL connection URL",
  },
  PORT: {
    type: "number",
    default: "3000",
  },
};

Note: TypeScript schema files (.ts) are not loaded directly by the CLI on Node.js 20. Use .js/.mjs output or run with a TypeScript loader.


🧩 Why env-safe-check?

Many apps rely on process.env directly.

That leads to:

  • ❌ Missing variables discovered in production
  • ❌ Silent failures
  • ❌ Wrong data types ("3000" instead of 3000)
  • ❌ Unclear error messages
  • ❌ Configuration drift across environments

env-safe-check solves this by validating everything at startup — clearly, strictly, and predictably.


🛠 API

1️⃣ Schema Mode (Recommended)

validateEnv(config: ValidateEnvOptions): Record<string, any>

Options

| Option | Description | |---------------|-------------| | schema | Object defining environment variables and their validation rules | | silent | Default: false. If true, suppresses output and does not throw |

Returns

Parsed and validated environment variables.

Throws

EnvValidationError (when silent: false and validation fails)


2️⃣ Simple Mode (Legacy)

validateEnv(required: string[]): void

Example:

validateEnv(['DATABASE_URL', 'API_KEY']);
  • Exits process with code 1 if any are missing
  • Prints colorful CLI messages

🧠 Variable Schema

interface VariableSchema {
  type?: 'string' | 'number' | 'boolean' | 'json';
  required?: boolean;        // default: true
  default?: string;
  validator?: (value: string) => boolean | string;
  validatorHint?: string;
  description?: string;
}

🎯 Advanced Examples

Custom Validator with Hint

validateEnv({
  schema: {
    WORKER_THREADS: {
      type: 'number',
      validator: (value) => {
        const num = Number(value);
        return num >= 1 && num <= 32
          ? true
          : 'Must be between 1 and 32';
      },
      validatorHint: 'integer between 1 and 32',
      description: 'Worker pool size',
    },
  },
});

Handling Errors Explicitly

import { validateEnv, EnvValidationError } from 'env-safe-check';

try {
  validateEnv({ schema: { DB_URL: 'string' } });
} catch (err) {
  if (err instanceof EnvValidationError) {
    console.error('Missing:', err.missing);
    console.error('Invalid:', err.invalid);
  }
}

🧪 Best Practices

  • ✅ Validate once at application startup
  • ✅ Always include description for team clarity
  • ✅ Provide validatorHint for custom validators
  • ✅ Keep silent: false in production
  • ✅ Explicitly mark optional variables with required: false

⚠️ Troubleshooting

| Issue | Fix | |-------|-----| | Boolean parsing fails | Use true, false, 1, or 0 | | Number parsing fails | Ensure numeric string (e.g., 3000) | | JSON parsing fails | Provide valid JSON ({"enabled": true}) | | Default not applied | Must set required: false |


🏗 Project Structure (For Contributors)

  • Source: src/ (TypeScript)
  • Output: dist/ (ESM)

Scripts

npm run build
npm run typecheck
npm test

📦 Publishing

  1. Bump version in package.json
  2. npm run build
  3. Verify main and types
  4. npm publish --access public

🤝 Contributing

Issues and PRs are welcome.

Before submitting:

  • Run type checks
  • Ensure tests pass
  • Keep changes focused and minimal