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 🙏

© 2025 – Pkg Stats / Ryan Hefner

env-sentry-lib

v1.1.5

Published

Type-safe environment variable validation with Zod

Readme

env-sentry-lib

CI Release Please codecov

Type-safe environment variable validation for Node.js with Zod.

Why?

Environment variables are loosely typed and error-prone. env-sentry-lib gives you:

  • Type Safety - Full TypeScript inference from your schema
  • Runtime Validation - Catch configuration errors at startup
  • Better Errors - Helpful error messages that tell you exactly what's wrong
  • Zero Config - Works out of the box with any Node.js project

Installation

npm install env-sentry-lib zod
# or
pnpm add env-sentry-lib zod
# or
yarn add env-sentry-lib zod

Quick Start

import { createEnv } from 'env-sentry-lib';
import { z } from 'zod';

// Define your environment schema
const env = createEnv({
  // Server config
  PORT: z.string().default('3000').transform(Number),
  HOST: z.string().default('localhost'),

  // Database
  DATABASE_URL: z.url(),

  // API Keys
  API_KEY: z.string().min(32),

  // Feature flags
  NODE_ENV: z
    .enum(['development', 'production', 'test'])
    .default('development'),
});

// Use with full type safety!
const port: number = env.PORT; // TypeScript knows this is a number
const dbUrl: string = env.DATABASE_URL; // TypeScript knows this is a string

// Start your server
console.log(`Server running on ${env.HOST}:${env.PORT}`);

Features

Type-Safe by Default

TypeScript automatically infers the correct types from your schema:

const env = createEnv({
  PORT: z.string().transform(Number),
  ENABLED: z.boolean(),
  TAGS: z.array(z.string()),
});

env.PORT; // type: number
env.ENABLED; // type: boolean
env.TAGS; // type: string[]

Default Values

Provide defaults for optional configuration:

const env = createEnv({
  PORT: z.string().default('3000').transform(Number),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
});

// If PORT is not set, uses 3000
// If LOG_LEVEL is not set, uses 'info'

Optional Values

Some values don't need defaults:

const env = createEnv({
  SENTRY_DSN: z.url().optional(),
  DEBUG_MODE: z.boolean().optional(),
});

env.SENTRY_DSN; // type: string | undefined
env.DEBUG_MODE; // type: boolean | undefined

Helpful Error Messages

When validation fails, you get actionable error messages:

Environment validation failed.
The application cannot start due to invalid environment variables.

Missing required variables:
  • DATABASE_URL
Action: Define these variables in your environment.

API Reference

createEnv(schema)

Creates a validated, type-safe environment object.

Parameters:

  • schema - An object where keys are environment variable names and values are Zod schemas

Returns:

  • A validated object with the same keys, typed according to the Zod schemas

Throws:

  • EnvValidationError - When validation fails

Example:

const env = createEnv({
  PORT: z.string().transform(Number),
  API_KEY: z.string(),
});

EnvValidationError

Custom error class thrown when environment validation fails.

import { createEnv, EnvValidationError } from 'env-sentry-lib';

try {
  const env = createEnv({ PORT: z.string() });
} catch (error) {
  if (error instanceof EnvValidationError) {
    console.error(error.message);
  }
}

Common Patterns

Number Validation

const env = createEnv({
  PORT: z.string().transform(Number).pipe(z.number().min(1000).max(65535)),
  MAX_CONNECTIONS: z.string().default('100').transform(Number),
});

URL Validation

const env = createEnv({
  DATABASE_URL: z.url(),
  REDIS_URL: z.url().optional(),
  API_ENDPOINT: z.url().startsWith('https://'),
});

Enum Values

const env = createEnv({
  NODE_ENV: z.enum(['development', 'staging', 'production']),
  LOG_LEVEL: z.enum(['debug', 'info', 'warn', 'error']),
});

Boolean Values

const env = createEnv({
  DEBUG: z.string().transform((val) => val === 'true'),
  ENABLE_CACHE: z
    .string()
    .transform((val) => val === 'true')
    .pipe(z.boolean()),
});

Array Values

const env = createEnv({
  ALLOWED_ORIGINS: z.string().transform((val) => val.split(',')),
  FEATURE_FLAGS: z
    .string()
    .transform((val) => val.split(','))
    .pipe(z.array(z.string())),
});

Framework Examples

Express.js

import express from 'express';
import { createEnv } from 'env-sentry-lib';
import { z } from 'zod';

const env = createEnv({
  PORT: z.string().default('3000').transform(Number),
  DATABASE_URL: z.url(),
});

const app = express();

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

Next.js

// config/env.ts
import { createEnv } from 'env-sentry-lib';
import { z } from 'zod';

export const env = createEnv({
  // Server-side only
  DATABASE_URL: z.url(),

  // Client-side (must start with NEXT_PUBLIC_)
  NEXT_PUBLIC_API_URL: z.url(),
});

Fastify

import fastify from 'fastify';
import { createEnv } from 'env-sentry';
import { z } from 'zod';

const env = createEnv({
  HOST: z.string().default('0.0.0.0'),
  PORT: z.string().default('3000').transform(Number),
});

const server = fastify();

server.listen({ host: env.HOST, port: env.PORT });

Comparison

| Feature | env-sentry-lib | envalid | dotenv | zod | t3-env | | ------------------ | -------------- | ------- | ------ | --- | ------ | | Type Inference | ✅ | ✅ | ❌ | ✅ | ✅ | | Runtime Validation | ✅ | ✅ | ❌ | ✅ | ✅ | | Helpful Errors | ✅ | ⚠️ | ❌ | ⚠️ | ✅ | | Framework Agnostic | ✅ | ✅ | ✅ | ✅ | ❌ | | Modern (2024+) | ✅ | ❌ | ✅ | ✅ | ✅ | | Zero Config | ✅ | ✅ | ✅ | ❌ | ❌ |

Roadmap

  • [ ] Secret masking (v0.2.0)
  • [ ] .env file loading (v0.2.0)
  • [ ] CLI tools (v0.3.0)
  • [ ] Cloud secrets integration (v0.4.0)
  • [ ] Documentation site (v1.0.0)

Contributing

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

License

This project is licensed under the MIT License — see the LICENSE.

Author

Built with ❤️ by mandy8055