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

@pawells/config

v2.2.0

Published

[![CI](https://github.com/PhillipAWells/common/actions/workflows/ci.yml/badge.svg)](https://github.com/PhillipAWells/common/actions/workflows/ci.yml) [![Node](https://img.shields.io/badge/node-%3E%3D22-brightgreen)](https://nodejs.org) [![npm version](htt

Readme

@pawells/config

CI Node npm version License: MIT

Description

Runtime configuration manager with Zod schema validation. Provides a singleton ConfigManager class for registering typed configuration schemas, setting values from multiple sources (defaults and runtime overrides), and retrieving strongly-typed configuration values with automatic validation. Supports environment variables, CLI arguments, and programmatic configuration.

Requirements

  • Node.js: 22.0.0 or later
  • TypeScript: 6.0.0 or later (if consuming from source)

Installation

Install from npm:

npm install @pawells/config

Or with yarn:

yarn add @pawells/config

Quick Start

Using CreateConfigSchema (Recommended)

The CreateConfigSchema factory is the recommended pattern for most use cases. It provides automatic environment variable parsing with a prefix and strongly-typed access to configuration values.

import { z } from 'zod/v4';
import { CreateConfigSchema } from '@pawells/config';

// Define your configuration schema
const SERVICE_CONFIG_SCHEMA = z.object({
  PORT: z.coerce.number().int().positive().default(3000),
  HOST: z.string().default('localhost'),
  DEBUG: z.boolean().default(false),
  DATABASE_URL: z.string().url(),
  API_TIMEOUT: z.coerce.number().int().positive().default(30000),
});

// Create a typed config object with 'SERVICE_' prefix
export const ServiceConfig = CreateConfigSchema(SERVICE_CONFIG_SCHEMA, 'SERVICE_');

// Register all schemas
ServiceConfig.Register();

// Parse environment variables (SERVICE_PORT, SERVICE_HOST, SERVICE_DEBUG, etc.)
ServiceConfig.ParseENV();

// Get typed values
const port = ServiceConfig.Get('PORT'); // number, typed
const host = ServiceConfig.Get('HOST'); // string, typed
const debug = ServiceConfig.Get('DEBUG'); // boolean, typed

console.log(`Server running on ${host}:${port}`);

Retrieving and Validating Values

// Get a typed configuration value (guaranteed type-safe)
const timeout = ServiceConfig.Get('API_TIMEOUT'); // number

// Validate a value before setting it
const isValid = ServiceConfig.Validate('PORT', '8080'); // true if valid

// Set configuration values at runtime
ServiceConfig.Set('DEBUG', true, 'OVERRIDE');

Advanced: Using ConfigManager Directly

For advanced scenarios where you need direct schema control or custom management, use ConfigManager:

import { ConfigManager } from '@pawells/config';
import { z } from 'zod/v4';

// Register individual schemas
ConfigManager.Register('DATABASE_URL', z.string().url(), 'postgresql://localhost/mydb');
ConfigManager.Register('API_KEY', z.string().min(32), 'default-key');

// Set and retrieve values
ConfigManager.Set('DATABASE_URL', process.env.DATABASE_URL);
const dbUrl = ConfigManager.Get('DATABASE_URL');

Error Handling

import {
  ConfigurationNotRegisteredError,
  ConfigurationNotSetError,
  ConfigurationError,
} from '@pawells/config';

try {
  // Attempt to retrieve a value
  const value = ServiceConfig.Get('UNKNOWN_KEY');
} catch (error) {
  if (error instanceof ConfigurationNotRegisteredError) {
    console.error('Configuration key not registered:', error.message);
  }
  if (error instanceof ConfigurationNotSetError) {
    console.error('Configuration value not set:', error.message);
  }
  if (error instanceof ConfigurationError) {
    console.error('Validation failed:', error.message);
  }
}

API Reference

CreateConfigSchema Factory (Recommended)

The CreateConfigSchema factory is the primary recommended API for most use cases. It creates a strongly-typed configuration schema object from a Zod schema.

Signature:

CreateConfigSchema<TSchema extends z.ZodRawShape>(
  schema: z.ZodObject<TSchema>,
  prefix: string
): IConfigSchemaObject<z.infer<typeof schema>>

Parameters:

  • schema — A Zod object schema defining your configuration structure
  • prefix — Environment variable prefix (e.g., 'SERVICE_' for SERVICE_PORT, SERVICE_HOST)

Returns: An IConfigSchemaObject with strongly-typed methods for configuration management.

IConfigSchemaObject Methods

These methods are returned by CreateConfigSchema and provide a strongly-typed interface to your configuration.

| Method | Signature | Description | |--------|-----------|-------------| | Register | Register(): void | Register all schema fields with ConfigManager, extracting default values from the schema. Call once at application startup. | | Get | Get<K extends TKeys>(key: K): TConfig[K] | Retrieve a typed configuration value by key. The return type is automatically inferred from your schema. | | Set | Set<K extends TKeys>(key: K, value: TConfig[K], source?: TConfigSource): void | Set a configuration value with optional source ('DEFAULT' or 'OVERRIDE', defaults to 'OVERRIDE'). Validates the value against the schema. | | Validate | Validate<K extends TKeys>(key: K, value: unknown): boolean | Validate a value against its schema without setting it. Returns true if valid, false otherwise. | | ParseENV | ParseENV(): void | Parse environment variables matching the configured prefix and set them as overrides. Prefixed variables are automatically discovered and parsed according to the schema. |

ConfigManager (Advanced)

For advanced scenarios requiring direct schema control or custom configuration management, use ConfigManager directly:

| Method | Signature | Description | |--------|-----------|-------------| | Register | Register(key: string, schema: ZodType, defaultValue: unknown): void | Register a configuration key with a Zod schema and default value. Validates the default value against the schema. | | Set | Set<T>(key: string, value: T, target?: 'DEFAULT' \| 'OVERRIDE'): void | Set a configuration value and validate against its schema. Default target is 'OVERRIDE'. | | Get | Get(key: string, source?: 'DEFAULT' \| 'OVERRIDE'): TConfigValueTypes | Retrieve a configuration value by key, validated against its schema. Returns resolved value merging defaults and overrides. | | GetSchema | GetSchema(key: string): ZodTypeAny | Retrieve the Zod schema for a configuration key for custom validation. | | Reset | Reset(): void | Clear all registered schemas and values (for testing). Internal API. |

Error Types

| Error | Description | |-------|-------------| | ConfigurationAlreadyRegisteredError | Thrown when attempting to register a key that already exists with a different schema. | | ConfigurationNotRegisteredError | Thrown when accessing or setting a key that was not registered with a schema. | | ConfigurationError | Thrown when configuration validation fails during registration, set, or get operations. Includes cause chain from Zod validation errors. | | ConfigurationNotSetError | Thrown when retrieving a configuration value that was never set. |

Type Exports

| Type | Description | |------|-------------| | TConfigValueTypes | Union type of all supported configuration value types: string, number, boolean, Date, string[], number[], boolean[], undefined, or null. | | TConfig | Internal map type: Map<string, TConfigValueTypes>. | | TConfigSource | Literal union type: 'DEFAULT' or 'OVERRIDE'. Controls which source layer a value is stored in or retrieved from. |

⚠️ Security Warning

Do not store sensitive values (API keys, database passwords, tokens, PII) directly as string literals in your code. Always load sensitive configuration from environment variables or secure vaults at startup.

When storing environment variable overrides, ensure the process environment itself is protected from inspection (e.g., via debugger or memory dumps).

Example:

// ✓ Good: Load from environment at startup
ConfigManager.Set('DATABASE_PASSWORD', process.env.DB_PASSWORD);

// ✗ Bad: Hardcoded secrets
ConfigManager.Register('DATABASE_PASSWORD', z.string(), 'hardcoded-password');

License

MIT — See LICENSE for details.