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

node-safe-env

v0.1.3

Published

A tiny schema-based env loader and validator for Node.js.

Readme

node-safe-env

npm npm downloads license node

Schema-based environment validation for Node.js and TypeScript.

Validate environment variables at startup, parse them into runtime types, and catch configuration problems before your app boots.

Why node-safe-env?

  • Fail fast during application startup.
  • Parse raw env strings into typed runtime values.
  • See aggregated validation issues in one error report.
  • Validate .env and .env.example usage from scripts or CI.
  • Inspect where values came from with debug tracing.

Features

  • Schema-based environment validation
  • TypeScript-friendly schema inference
  • Automatic parsing for numbers, booleans, arrays, dates
  • Nested schemas with flattened env keys
  • CLI validation for env and .env.example
  • Aggregated validation errors
  • Debug tracing for env source resolution

Try it instantly

You can run the CLI without installing the package globally. The quickest way to try node-safe-env is with npx.

npx node-safe-env --help

Validate environment variables:

npx node-safe-env validate --schema ./env.schema.ts

Validate .env.example:

npx node-safe-env validate-example --schema ./env.schema.ts

Install

npm install node-safe-env

Examples

Runnable examples are available in the repository and mirror common usage patterns.

  • examples/basic - minimal schema validation
  • examples/nested - nested schema with flattened env keys
  • examples/advanced - arrays, custom parsing, debug mode, masking
  • examples/cli-schema - schema module intended for CLI validation

Quick Start

Define a schema:

import { createEnv, defineEnv } from "node-safe-env";

const schema = defineEnv({
  APP_NAME: { type: "string", required: true },
  PORT: { type: "port", default: 3000 },
  DEBUG: { type: "boolean", default: false },
  NODE_ENV: {
    type: "enum",
    values: ["development", "test", "production"],
    default: "development",
  },
} as const);

Use it at runtime:

const env = createEnv(schema);

env.APP_NAME; // string
env.PORT; // number
env.DEBUG; // boolean
env.NODE_ENV; // "development" | "test" | "production"

What this gives you:

  • required: true means the value must exist.
  • default is used when a value is missing.
  • type controls parsing and validation.
  • The returned env object is strongly typed from your schema.

Example .env:

APP_NAME=DemoApp
PORT=4000
DEBUG=true
NODE_ENV=development

Values are read as strings from the environment and then parsed according to your schema.

What Is a Schema in node-safe-env?

A schema is an object where each key maps to a rule object.

Each rule describes:

  • What type the value should be with type
  • Whether it must be present with required
  • What to use if it is missing with default
  • Any rule-specific options such as enum values, array settings, or a custom parser

Use defineEnv() when you want better literal type inference and a reusable exported schema module.

// env.schema.ts
import { defineEnv } from "node-safe-env";

export const schema = defineEnv({
  PORT: { type: "port", default: 3000 },
  ADMIN_EMAIL: { type: "email", required: true },
} as const);

When to use node-safe-env

Use this library if you want to:

  • validate environment variables at application startup
  • enforce typed configuration in Node.js or TypeScript projects
  • ensure .env.example stays aligned with your configuration schema
  • detect configuration issues early in CI pipelines

Common Use Cases

  • App startup validation: load and validate env once during bootstrap.
  • CI checks for .env.example: fail pull requests when required keys are missing or stale.
  • Debugging source issues: use debug output to understand where values were loaded from.

Value at a Glance

node-safe-env is a schema-based env validator with:

  • TypeScript-friendly schema inference
  • CLI commands for runtime and .env.example validation
  • Structured, aggregated validation errors
  • Source tracing and debug visibility

Nested Schemas

Schemas can be nested, but environment variable names are always flattened. Keys are generated by joining object path segments with _ and converting each segment to uppercase. The library does not convert camelCase to snake_case, so server.allowedHosts becomes SERVER_ALLOWEDHOSTS, not SERVER_ALLOWED_HOSTS.

Examples:

  • server.port -> SERVER_PORT
  • database.url -> DATABASE_URL
  • server.allowedHosts -> SERVER_ALLOWEDHOSTS
const env = createEnv({
  server: {
    port: { type: "port", default: 3000 },
    allowedHosts: { type: "array", required: true },
  },
  database: {
    url: { type: "string", required: true },
  },
});

console.log(env.server.port);
SERVER_PORT=4000
SERVER_ALLOWEDHOSTS=localhost,example.com
DATABASE_URL=postgres://localhost:5432/app

CLI

node-safe-env includes two CLI commands:

  • validate: validate current environment values against your schema
  • validate-example: validate .env.example coverage against your schema

You can run the CLI without installing the package globally:

npx node-safe-env --help

Most common commands:

npx node-safe-env validate --schema ./env.schema.ts
npx node-safe-env validate-example --schema ./env.schema.ts
node-safe-env validate --schema ./env.schema.ts
node-safe-env validate-example --schema ./env.schema.ts
node-safe-env validate --schema ./dist/env.schema.js --strict

CLI schema files

The --schema module supports both JavaScript and TypeScript files:

  • JavaScript: .js, .mjs, .cjs
  • TypeScript: .ts, .mts, .cts

Accepted export shapes:

  • Default export
  • Named export schema

.env.example Validation

.env.example should contain all keys defined in your schema so new environments and CI checks stay aligned with your application configuration.

Example .env.example:

PORT=3000
DEBUG=false
NODE_ENV=development

Validate a real file:

import { validateExampleEnvFile } from "node-safe-env";

const issues = validateExampleEnvFile(schema, {
  cwd: process.cwd(),
  exampleFile: ".env.example",
});

Validate an in-memory object:

import { validateExampleEnv } from "node-safe-env";

const issues = validateExampleEnv(schema, {
  PORT: "",
});

Rule Types

Supported type values:

  • string
  • number
  • boolean
  • enum
  • url
  • port
  • json
  • int
  • float
  • array
  • email
  • date
  • custom

Loading Order

When options.source is not provided, values are merged in this order and later sources win:

  1. .env
  2. .env.local
  3. .env.<NODE_ENV>
  4. Custom file from options.envFile
  5. process.env

Debug Mode

Use debug mode to inspect how values were loaded and resolved.

import { createEnv, type EnvDebugReport } from "node-safe-env";

const reports: EnvDebugReport[] = [];

createEnv(schema, {
  debug: {
    logger: (report) => reports.push(report),
  },
});

Or log debug reports directly:

createEnv(schema, { debug: true });

Strict Mode

createEnv(schema, { strict: true });

Strict mode reports unknown environment keys as validation issues.

Error Handling

Validation issues are aggregated and thrown as EnvValidationError.

import { createEnv, EnvValidationError } from "node-safe-env";

try {
  createEnv(schema);
} catch (error) {
  if (error instanceof EnvValidationError) {
    console.error(error.issues);
  }
}

API Summary

Exports:

  • createEnv
  • defineEnv
  • EnvValidationError
  • maskEnv
  • mergeSources
  • traceEnv
  • validateExampleEnv
  • validateExampleEnvFile
  • readEnvFileSource
  • resolveExampleEnvPath

createEnv(schema, options?):

{
  source?: Record<string, string | undefined>;
  cwd?: string;
  nodeEnv?: string;
  envFile?: string;
  strict?: boolean;
  debug?: boolean | { logger?: (report: EnvDebugReport) => void };
}

Compatibility

  • Node.js >= 18
  • ESM and CommonJS builds
  • TypeScript declarations included

Development

npm run lint
npm run build
npm run typecheck
npm run test
npm run test:watch
npm run check

License

MIT