@pawells/config
v2.2.0
Published
[](https://github.com/PhillipAWells/common/actions/workflows/ci.yml) [](https://nodejs.org) [, 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/configOr with yarn:
yarn add @pawells/configQuick 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 structureprefix— Environment variable prefix (e.g.,'SERVICE_'forSERVICE_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.
