MCPcopy Index your code
hub / github.com/alexmarqs/zod-config

github.com/alexmarqs/zod-config @v1.4.0

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.4.0 ↗ · + Follow
49 symbols 454 edges 83 files 0 documented · 0% updated 2mo agov1.4.0 · 2025-10-25★ 1361 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Zod logo

Zod Config

Load configuration variables from multiple sources type safely using Zod.

NPM

The new major version supports both Zod 4 and Zod 3 out of the box. Check the compatibility section for more details.

Features

  • 👮‍♂️ Type safety. Zod Config uses Zod;
  • 🤌 Tiny. Zod Config is a tiny library with no dependencies, tree-shaking friendly;
  • Flexible. Combine multiple adapters to load the configuration from different sources. We deeply merge the configuration from different sources, following the order of the adapters provided; Create your own adapters easily; Use the callback functions to handle errors and success due to the async nature of the adapters;
  • 🪴 Easy to use. Zod Config is designed to be easy to use, with a simple API;
  • 🔄 Async / Sync support. Zod Config provides both asynchronous and synchronous APIs to fit different application needs;

Install

npm install zod-config zod # npm
pnpm add zod-config zod # pnpm
yarn add zod-config zod # yarn

Table of contents:

Quick Start

Zod Config provides both asynchronous and synchronous APIs for loading configuration:

  • loadConfig: Asynchronous function that takes a Zod Object schema and returns a promise resolving to the validated configuration object;
  • loadConfigSync: Synchronous version that takes the same configuration but returns the result directly without a promise;

Note: loadConfigSync only supports synchronous adapters and schemas. For details on compatibility, see Synchronous loading.

Here are the available configuration options:

Here are the available configuration options for loadConfig and loadConfigSync:

Property Type Description Required Global Adapter
schema AnyZodObject A Zod Object schema to validate the configuration. N/A N/A
adapters Array<Adapter \| SyncAdapter> \| Adapter \| SyncAdapter Adapter(s) to load the configuration from. If not provided, process.env will be used. N/A N/A
onError (error: InferredErrorConfig<T>) => void) A callback to be called when an error occurs.
onSuccess (data: InferredDataConfig<S>) => void A callback to be called when the configuration is loaded successfully.
logger Logger A custom logger to be used to log messages. By default, it uses console.
keyMatching 'strict' \| 'lenient' How to match keys between the schema and the data of the adapters. By default, it uses strict.
silent boolean Whether to suppress errors. By default, it is false.
transform (obj: { key: string; value: unknown }) => { key: string; value: unknown } \| false Function to transform key-value pairs before processing. If the function returns false, the key-value pair will be dropped.

Note: Options marked as both "Global" and "Adapter" can be set at the global level (affecting all adapters) or at individual adapter level (affecting only that adapter). When both are provided, the adapter-level option takes precedence. For specific adapter options, check the section of the adapter you are using.

From the package we also expose the necessary types in case you want to use them in your own adapters. Some of the options are shared between the global config and the adapter config, so you can use them in your own adapters as well.

This library provides some built in adapters to load the configuration from different sources via modules. You can easily import them from zod-config/<built-in-adapter-module-name>.

Compatibility

Zod Config supports both Zod 4 and Zod 3 out of the box. To start using it, just make sure you have the correct versions of zod-config (zod-config@^1.0.0) and zod (zod@^3.25.0 or zod@^4.0.0)!

// Using Zod 4
import { z } from "zod/v4"; // for ^4.0.0 zod versions, you can import from "zod" instead
// Using Zod 4 Mini
import { z } from "zod/v4-mini"; // for ^4.0.0 zod versions, you can import from "zod/mini" instead
// Using Zod 3
import { z } from "zod/v3";

import { loadConfig } from "zod-config";
import { envAdapter } from "zod-config/env-adapter";

const schema = z.object({
  name: z.string(),
});

const config = await loadConfig({
  schema,
  adapters: [
    envAdapter(),
  ],
});

Basic Usage

Default Adapter

By default, Zod Config will load the configuration from process.env, no need to provide any adapter.

import { z } from 'zod';
import { loadConfig } from 'zod-config';

const schemaConfig = z.object({
  port: z.string().regex(/^\d+$/),
  host: z.string(),
});

const config = await loadConfig({
  schema: schemaConfig
});

// config is now type safe!
console.log(config.port)
console.log(config.host)

Built In Adapters

Env Adapter

Loads the configuration from process.env or a custom object, allowing you to filter the keys using a regex (this can be useful when you have multiple adapters and you want to filter the keys to avoid conflicts or just to keep only the keys you need to process). To support nested objects, you can use the nestingSeparator property that will be used to create nested objects from flat keys based on the separator.

import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { envAdapter } from 'zod-config/env-adapter';

const schemaConfig = z.object({
  MY_APP_PORT: z.string().regex(/^\d+$/),
  MY_APP_HOST: z.string(),
});

// using default env (process.env)
const config = await loadConfig({
  schema: schemaConfig,
  adapters: envAdapter(),
});

// using custom env + filter regex to match only the keys we need
const customConfig = await loadConfig({
  schema: schemaConfig,
  adapters: envAdapter({ 
    regex: /^MY_APP_/,
    customEnv: {
      MY_APP_PORT: '3000',
      MY_APP_HOST: 'localhost',
      IGNORED_KEY: 'ignored',
    }})
});

// using nesting separator to create nested objects
const nestedConfig = await loadConfig({
  schema: z.object({
    database: z.object({
      host: z.string(),
      port: z.string(),
    }),
  }),
  adapters: envAdapter({
    customEnv: {
      'database.host': 'localhost',
      'database.port': '5432',
    },
    nestingSeparator: '.',
  }),
});

JSON Adapter

Loads the configuration from a json file.

import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { jsonAdapter } from 'zod-config/json-adapter';
import path from 'path';

const schemaConfig = z.object({
  MY_APP_PORT: z.string().regex(/^\d+$/),
  MY_APP_HOST: z.string(),
});

const filePath = path.join(__dirname, 'config.json');

const config = await loadConfig({
  schema: schemaConfig,
  adapters: jsonAdapter({ path: filePath }),
});

// using filter regex to match only the keys we need
const customConfig = await loadConfig({
  schema: schemaConfig,
  adapters: jsonAdapter({ 
    path: filePath,
    regex: /^MY_APP_/,
  }),
});

JSON5 Adapter

Loads the configuration from a json5 file. In order to use this adapter, you need to install json5 (peer dependency), if you don't have it already.

import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { json5Adapter } from 'zod-config/json5-adapter';
import path from 'path';

/** content of config.json5
{
  // Server settings
  host: 'localhost',       // Single quotes + unquoted key
  port: 3000,              // Trailing comma
  allowedIPs: [
    '192.168.0.1',
    '10.0.0.1',  // Local access
  ]
}
*/

const filePath = path.join(__dirname, 'config.json5');

const schemaConfig = z.object({
  host: z.string(),
  port: z.number(),
  allowedIPs: z.array(z.string()),
});

const config = await loadConfig({
  schema: schemaConfig,
  adapters: json5Adapter({ path: filePath }),
});

YAML Adapter

Loads the configuration from a yaml file. In order to use this adapter, you need to install yaml (peer dependency), if you don't have it already.

npm install yaml
import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { yamlAdapter } from 'zod-config/yaml-adapter';
import path from 'path';

const schemaConfig = z.object({
  MY_APP_PORT: z.string().regex(/^\d+$/),
  MY_APP_HOST: z.string(),
});

const filePath = path.join(__dirname, 'config.yaml');

const config = await loadConfig({
  schema: schemaConfig,
  adapters: yamlAdapter({ path: filePath }),
});

// using filter regex to match only the keys we need
const customConfig = await loadConfig({
  schema: schemaConfig,
  adapters: yamlAdapter({ 
    path: filePath,
    regex: /^MY_APP_/,
  }),
});

TOML Adapter

Loads the configuration from a toml file. In order to use this adapter, you need to install smol-toml (peer dependency), if you don't have it already.

npm install smol-toml
import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { tomlAdapter } from 'zod-config/toml-adapter';
import path from 'path';

const schemaConfig = z.object({
  MY_APP_PORT: z.string().regex(/^\d+$/),
  MY_APP_HOST: z.string(),
});

const filePath = path.join(__dirname, 'config.toml');

const config = await loadConfig({
  schema: schemaConfig,
  adapters: tomlAdapter({ path: filePath }),
});

// using filter regex to match only the keys we need
const customConfig = await loadConfig({
  schema: schemaConfig,
  adapters: tomlAdapter({ 
    path: filePath,
    regex: /^MY_APP_/,
  }),
});

Dotenv Adapter

Loads the configuration from a .env file. In order to use this adapter, you need to install dotenv (peer dependency), if you don't have it already. To support nested objects, you can use the nestingSeparator property that will be used to create nested objects from flat keys based on the separator.

npm install dotenv
import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { dotEnvAdapter } from 'zod-config/dotenv-adapter';
import path from 'path';

const schemaConfig = z.object({
  MY_APP_PORT: z.string().regex(/^\d+$/),
  MY_APP_HOST: z.string(),
});

const filePath = path.join(__dirname, '.env');

const config = await loadConfig({
  schema: schemaConfig,
  adapters: dotEnvAdapter({ path: filePath }),
});

// using filter regex to match only the keys we need
const customConfig = await loadConfig({
  schema: schemaConfig,
  adapters: dotEnvAdapter({ 
    path: filePath,
    regex: /^MY_APP_/,
  }),
});

// using nesting separator to create nested objects
// .env file content: DATABASE_HOST=localhost\nDATABASE_PORT=5432
const nestedConfig = await loadConfig({
  schema: z.object({
    DATABASE: z.object({
      HOST: z.string(),
      PORT: z.string(),
    }),
  }),
  adapters: dotEnvAdapter({
    path: filePath,
    nestingSeparator: '_',
  }),
});

Script Adapter

Loads configuration from TypeScript (.ts), JavaScript (.js), or JSON (.json) files. The .ts and .js files must export a default object with the configuration data.

import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { scriptAdapter } from 'zod-config/script-adapter';
import path from 'path';

const schemaConfig = z.object({
  port: z.string().regex(/^\d+$/),
  host: z.string(),
});

// config.ts might contain: export default { port: '3000', host: 'localhost' }
const filePath = path.join(__dirname, 'config.ts');

const config = await loadConfig({
  schema: schemaConfig,
  adapters: scriptAdapter({
    path: filePath,
  }),
});

Directory Adapter

Loads configuration from a directory containing multiple configuration files (usually used in combination with the scriptAdapter and/or other file related adapter). Inspired by node-config, the files in the config directory are loaded in the following order:

``` default.EXT default-{instance}.EXT {deployment}.EXT {deployment}-{instance}.EXT {short_hostname}.EXT {short_hostname}-{instance}.EXT {short_hostname}-{deployment}.EXT

Core symbols most depended-on inside this repo

loadConfig
called by 175
src/lib/config.ts
jsonAdapter
called by 37
src/lib/adapters/json-adapter/index.ts
envAdapter
called by 34
src/lib/adapters/env-adapter/index.ts
inlineAdapter
called by 28
tests/fixtures/utils-fixtures.ts
loadConfigSync
called by 23
src/lib/config-sync.ts
dotEnvAdapter
called by 21
src/lib/adapters/dotenv-adapter/index.ts
applyDataTransformation
called by 20
src/lib/utils/data-transformation.ts
applyKeyMatching
called by 20
src/lib/utils/key-matchers.ts

Shape

Function 49

Languages

TypeScript100%

Modules by API surface

src/lib/utils/key-matchers.ts15 symbols
src/lib/adapters/directory-adapter/variables.ts5 symbols
src/lib/adapters/directory-adapter/resolution-and-load-order.ts3 symbols
src/lib/utils/filtered-data.ts2 symbols
src/lib/config.ts2 symbols
src/lib/config-sync.ts2 symbols
tests/zod-4/directory-adapter/variables.test.ts1 symbols
tests/zod-4/data-transformation.test.ts1 symbols
tests/fixtures/utils-fixtures.ts1 symbols
src/lib/utils/resolved-config.ts1 symbols
src/lib/utils/process-adapter-data.ts1 symbols
src/lib/utils/nesting-separator.ts1 symbols

Datastores touched

mydbDatabase · 1 repos

For agents

$ claude mcp add zod-config \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page