# AWS Secrets Manager adapter (https://zod-config.alexandremarques.io/docs/adapters/aws-secrets-manager) Loads the configuration from an [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) secret. ## Install [#install] This adapter needs the `@aws-sdk/client-secrets-manager` peer dependency, if you don't have it already: ```package-install @aws-sdk/client-secrets-manager ``` The adapter is asynchronous, so use it with `loadConfig`. ## Usage [#usage] ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { awsSecretsManagerAdapter } from 'zod-config/aws-secrets-manager-adapter'; // JSON secret {"DB_HOST": "...", "DB_PASSWORD": "..."} is loaded as key-value pairs const config = await loadConfig({ schema: z.object({ DB_HOST: z.string(), DB_PASSWORD: z.string() }), adapters: awsSecretsManagerAdapter({ secretId: 'my-app/database' }), }); // `key` exposes the whole secret as a string (like an env var) const stripe = await loadConfig({ schema: z.object({ STRIPE_KEY: z.string() }), adapters: awsSecretsManagerAdapter({ secretId: 'my-app/stripe-key', key: 'STRIPE_KEY' }), }); ``` Region, credentials and endpoint come from the AWS SDK defaults (`AWS_REGION`, `AWS_ENDPOINT_URL`, IAM role, ...). To configure them yourself, pass `client: new SecretsManagerClient({ ... })`. **IAM permissions:** `secretsmanager:GetSecretValue` on the secret, plus `kms:Decrypt` on the key if the secret is encrypted with a customer-managed KMS key. Remote reads cost a network call each time `loadConfig` runs. Load the config once and reuse it: see [Load once](/docs/guides/load-once). ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `secretId` | `string` | Name or ARN of the secret. Required. | | `key` | `string` | Expose the raw secret value (as a string) under this key instead of merging its JSON entries. Parse it in the schema if needed, e.g. `z.string().transform(JSON.parse)`. | | `client` | `SecretsManagerClient` | Client to use. Defaults to a shared client that resolves region and credentials through the AWS SDK default chain. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # AWS SSM adapter (https://zod-config.alexandremarques.io/docs/adapters/aws-ssm) Loads the configuration from [AWS SSM Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html), either a single parameter (`name`) or every parameter under a `path`. `SecureString` values are decrypted. ## Install [#install] This adapter needs the `@aws-sdk/client-ssm` peer dependency, if you don't have it already: ```package-install @aws-sdk/client-ssm ``` The adapter is asynchronous, so use it with `loadConfig`. ## Usage [#usage] ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { awsSsmAdapter } from 'zod-config/aws-ssm-adapter'; // single parameter: works like the Secrets Manager adapter (JSON or `key`) const config = await loadConfig({ schema: z.object({ API_KEY: z.string() }), adapters: awsSsmAdapter({ name: '/my-app/api-key', key: 'API_KEY' }), }); // path: /my-app/prod/LOG_LEVEL, /my-app/prod/db/HOST, /my-app/prod/db/PORT const appConfig = await loadConfig({ schema: z.object({ LOG_LEVEL: z.string(), db: z.object({ HOST: z.string(), PORT: z.coerce.number() }), }), adapters: awsSsmAdapter({ path: '/my-app/prod' }), }); // { LOG_LEVEL: 'info', db: { HOST: 'db.internal', PORT: 5432 } } ``` With `path`, the prefix is stripped, sub-paths become nested objects and results are paginated. A parameter whose name is also a prefix of another parameter's name (e.g. `/my-app/prod/db` and `/my-app/prod/db/HOST`) cannot be loaded from the same path, since `db` would have to be both a value and an object; this raises a nested key conflict error. Exclude the conflicting name with `regex`, and load that parameter with a second adapter under a different key. **IAM permissions:** `ssm:GetParameter` for `name`, `ssm:GetParametersByPath` for `path` (granted on the path itself, e.g. `arn:aws:ssm:::parameter/my-app/prod`). `SecureString` parameters encrypted with a customer-managed KMS key also need `kms:Decrypt` on that key. Remote reads cost a network call each time `loadConfig` runs. Load the config once and reuse it: see [Load once](/docs/guides/load-once). ## Options [#options] Pass either `name` or `path`, not both. | Option | Type | Description | | --- | --- | --- | | `name` | `string` | Name or ARN of a single parameter. | | `key` | `string` | With `name` only: expose the raw parameter value (as a string) under this key instead of merging its JSON entries. Parse it in the schema if needed, e.g. `z.string().transform(JSON.parse)`. | | `path` | `string` | Load every parameter under this path (recursively). `regex` is matched against the stripped names before nesting, e.g. `db/HOST`. | | `client` | `SSMClient` | Client to use. Defaults to a shared client that resolves region and credentials through the AWS SDK default chain. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # Write your own adapter (https://zod-config.alexandremarques.io/docs/adapters/custom) An adapter is a plain object with a `name` and a `read` function. Zod Config calls `read`, merges what it returns with the other adapters, and validates the result with your schema. The package exports the `Adapter` and `SyncAdapter` types for this. ## Asynchronous adapter [#asynchronous-adapter] Implement `Adapter` when `read` returns a promise, for example to call an API. It works with `loadConfig`: ```ts twoslash import { z } from 'zod'; import { loadConfig, type Adapter } from 'zod-config'; const httpAdapter = (url: string): Adapter => ({ name: 'http adapter', read: async () => { const response = await fetch(url); return response.json(); }, }); const config = await loadConfig({ schema: z.object({ featureFlag: z.boolean() }), adapters: httpAdapter('https://example.com/config.json'), }); ``` ## Synchronous adapter [#synchronous-adapter] Implement `SyncAdapter` when `read` returns the data directly. It works with both `loadConfig` and [`loadConfigSync`](/docs/guides/sync-loading); `loadConfigSync` only accepts `SyncAdapter`s. ```ts twoslash import { z } from 'zod'; import { loadConfigSync, type SyncAdapter } from 'zod-config'; const argvAdapter = (): SyncAdapter => ({ name: 'argv adapter', read: () => Object.fromEntries( process.argv .filter((arg) => arg.startsWith('--') && arg.includes('=')) .map((arg) => arg.slice(2).split('=', 2)), ), }); const config = loadConfigSync({ schema: z.object({ port: z.coerce.number().default(3000) }), adapters: argvAdapter(), }); ``` ## What an adapter can set [#what-an-adapter-can-set] | Property | Type | Description | | --- | --- | --- | | `name` | `string` | Name of the adapter, used in warnings. Required. | | `read` | `() => Promise` (`Adapter`) or `() => data` (`SyncAdapter`) | Returns the raw configuration data. Required. | | `nestingSeparator` | `string` | Build nested objects from flat keys using this separator. Only top-level keys are split. | | `silent` | `boolean` | Don't log a warning when `read` throws. | | `keyMatching` | `'strict' \| 'lenient'` | How to match keys to the schema. | | `transform` | `(obj: { key: string; value: unknown }) => { key: string; value: unknown } \| false` | Transform or drop key-value pairs before processing. | If `read` throws, Zod Config logs a warning (unless `silent`) and continues with empty data from that adapter. Validation then decides whether loading fails. To accept the same options as the built-in adapters, take them as parameters and set them on the returned object. Filtering by `regex` is up to your `read` function: it is not applied automatically. Built an adapter others could use? Open a PR or an issue on [GitHub](https://github.com/alexmarqs/zod-config). # Directory adapter (https://zod-config.alexandremarques.io/docs/adapters/directory) Loads configuration from a directory containing multiple configuration files, usually together with the [script adapter](/docs/adapters/script) or another file adapter. Inspired by [node-config](https://github.com/node-config/node-config/wiki/Configuration-Files#file-load-order), the files in the config directory are loaded in the following order: ```txt default.EXT default-{instance}.EXT {deployment}.EXT {deployment}-{instance}.EXT {short_hostname}.EXT {short_hostname}-{instance}.EXT {short_hostname}-{deployment}.EXT {short_hostname}-{deployment}-{instance}.EXT {hostname}.EXT {hostname}-{instance}.EXT {hostname}-{deployment}.EXT {hostname}-{deployment}-{instance}.EXT local.EXT local-{instance}.EXT local-{deployment}.EXT local-{deployment}-{instance}.EXT ``` Where: - `EXT` is the file extension, e.g. `ts`, `js`, `json`; - `instance` is the `NODE_APP_INSTANCE` environment variable; - `deployment` is the `NODE_CONFIG_ENV` or `NODE_ENV` environment variable; - `hostname` is the `HOST` or `HOSTNAME` environment variable, or `os.hostname()`; - `short_hostname` is the first part of the hostname. This adapter is useful when you keep the configuration for each environment in version control. ## Install [#install] No extra dependency. The directory adapter is asynchronous, so use it with `loadConfig`. ## Usage [#usage] ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { directoryAdapter } from 'zod-config/directory-adapter'; import { scriptAdapter } from 'zod-config/script-adapter'; import path from 'path'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const directories = [path.join(__dirname, 'config-dir')]; const config = await loadConfig({ schema: schemaConfig, adapters: directoryAdapter({ paths: directories, adapters: [ { // Restrict adapter to handle only ts files extensions: ['.ts'], // Use the scriptAdapter for handling .ts files adapterFactory: (filePath: string) => scriptAdapter({ path: filePath, }), }, // { // Add here other adapters for other file types if needed // } ], }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `paths` | `string \| string[]` | Directory or directories to load files from. Required. | | `adapters` | `AdapterSpecifier \| AdapterSpecifier[]` | Which adapter reads which file extensions. Required. | Each `AdapterSpecifier` has: | Field | Type | Description | | --- | --- | --- | | `extensions` | `string[]` | File extensions this adapter handles, e.g. `['.ts']`. An extension can appear in only one specifier. | | `adapterFactory` | `(path: string) => Adapter` | Creates the adapter for one file. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # Dotenv adapter (https://zod-config.alexandremarques.io/docs/adapters/dotenv) Loads the configuration from a `.env` file. To build nested objects from flat keys, set `nestingSeparator`. ## Install [#install] This adapter needs the `dotenv` peer dependency, if you don't have it already: ```package-install dotenv ``` The dotenv adapter is synchronous, so it also works with [`loadConfigSync`](/docs/guides/sync-loading). ## Usage [#usage] ```ts twoslash 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: '_', }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `path` | `string` | Path to the `.env` file. Required. | | `nestingSeparator` | `string` | Separator used to build nested objects from flat keys, e.g. `_`. Only top-level keys are split. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # Env adapter (https://zod-config.alexandremarques.io/docs/adapters/env) Loads the configuration from `process.env` or a custom object. Use `regex` to keep only the keys you need, which helps avoid conflicts when you combine several adapters. To build nested objects from flat keys, set `nestingSeparator`. ## Install [#install] No extra dependency. The env adapter is synchronous, so it also works with [`loadConfigSync`](/docs/guides/sync-loading). ## Usage [#usage] ```ts twoslash 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: '.', }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `customEnv` | `Record` | Object to read instead of `process.env`. | | `nestingSeparator` | `string` | Separator used to build nested objects from flat keys, e.g. `.` or `_`. Only top-level keys are split. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. For apps with a browser bundle (Next.js, Vite, Astro, TanStack Start), use [type-safe environment variables](/docs/env) instead: they separate server and client variables. # Adapters (https://zod-config.alexandremarques.io/docs/adapters) An adapter reads configuration from one source (environment variables, a file, AWS) and hands the raw data to Zod Config, which merges it and validates it with your schema. ## Default adapter [#default-adapter] By default, Zod Config loads the configuration from `process.env`, so you don't need to provide any adapter: ```ts twoslash 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 [#built-in-adapters] Built-in adapters are imported from `zod-config/`. Some need a peer dependency, which you install yourself. | Adapter | Import | Reads | Peer dependency | Sync | | --- | --- | --- | --- | --- | | [Env](/docs/adapters/env) | `zod-config/env-adapter` | `process.env` or a custom object | none | ✅ | | [JSON](/docs/adapters/json) | `zod-config/json-adapter` | a `.json` file | none | ✅ | | [JSON5](/docs/adapters/json5) | `zod-config/json5-adapter` | a `.json5` file | `json5` | ✅ | | [YAML](/docs/adapters/yaml) | `zod-config/yaml-adapter` | a `.yaml` file | `yaml` | ✅ | | [TOML](/docs/adapters/toml) | `zod-config/toml-adapter` | a `.toml` file | `smol-toml` | ✅ | | [Dotenv](/docs/adapters/dotenv) | `zod-config/dotenv-adapter` | a `.env` file | `dotenv` | ✅ | | [Script](/docs/adapters/script) | `zod-config/script-adapter` | a `.ts`, `.js` or `.json` file | `jiti`, optional, for TypeScript | ❌ | | [Directory](/docs/adapters/directory) | `zod-config/directory-adapter` | a directory of config files | none | ❌ | | [AWS Secrets Manager](/docs/adapters/aws-secrets-manager) | `zod-config/aws-secrets-manager-adapter` | an AWS Secrets Manager secret | `@aws-sdk/client-secrets-manager` | ❌ | | [AWS SSM](/docs/adapters/aws-ssm) | `zod-config/aws-ssm-adapter` | AWS SSM Parameter Store | `@aws-sdk/client-ssm` | ❌ | Synchronous adapters also work with [`loadConfigSync`](/docs/guides/sync-loading). Need another source? [Write your own adapter](/docs/adapters/custom). ## Combining adapters [#combining-adapters] Pass an array to read from several sources. The results are **deeply merged in the order of the adapters**, so later adapters override earlier ones. See [Combine multiple adapters](/docs/guides/combine-adapters). The keys `__proto__` and `constructor` are skipped when merging, and so are nested keys with a `__proto__` or `constructor` segment when a nesting separator is used. ## Shared adapter options [#shared-adapter-options] Every built-in adapter accepts these options on top of its own: | Option | Type | Description | | --- | --- | --- | | `regex` | `RegExp` | Only keep keys that match this regular expression. | | `silent` | `boolean` | Don't log a warning when this adapter fails. See [Silent mode](/docs/guides/silent-mode). | | `keyMatching` | `'strict' \| 'lenient'` | How to match keys to the schema. See [Lenient key matching](/docs/guides/lenient-key-matching). | | `transform` | `(obj: { key: string; value: unknown }) => { key: string; value: unknown } \| false` | Transform or drop key-value pairs before processing. See [Transform](/docs/guides/transform). | `silent`, `keyMatching` and `transform` can also be set globally on `loadConfig`. When both are set, the adapter-level option takes precedence. # JSON adapter (https://zod-config.alexandremarques.io/docs/adapters/json) Loads the configuration from a `json` file. ## Install [#install] No extra dependency. The JSON adapter is synchronous, so it also works with [`loadConfigSync`](/docs/guides/sync-loading). ## Usage [#usage] ```ts twoslash 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_/, }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `path` | `string` | Path to the JSON file. Required. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # JSON5 adapter (https://zod-config.alexandremarques.io/docs/adapters/json5) Loads the configuration from a `json5` file. ## Install [#install] This adapter needs the `json5` peer dependency, if you don't have it already: ```package-install json5 ``` The JSON5 adapter is synchronous, so it also works with [`loadConfigSync`](/docs/guides/sync-loading). ## Usage [#usage] ```json5 title="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 ], } ``` ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { json5Adapter } from 'zod-config/json5-adapter'; import path from 'path'; 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 }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `path` | `string` | Path to the JSON5 file. Required. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # Script adapter (https://zod-config.alexandremarques.io/docs/adapters/script) 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. Relative paths resolve from the working directory. ## Install [#install] No extra dependency for `.js` and `.json` files. The script adapter is asynchronous, so use it with `loadConfig`. ### TypeScript files [#typescript-files] `.ts` files load with Node's built-in type stripping (Node 22.18 and later). If that fails, they load with [jiti](https://github.com/unjs/jiti) instead, for example: - on older Node versions; - with syntax that type stripping does not support, such as `enum`; - with extensionless imports (`import { db } from './db'`); - with path aliases from `tsconfig.json`. To use this fallback, install `jiti`, version 2 or later (path aliases need 2.7 or later), if you don't have it already: ```package-install jiti ``` ## Usage [#usage] ```ts twoslash 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, }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `path` | `string` | Path to the `.ts`, `.js` or `.json` file, absolute or relative to the working directory. Required. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. To load several files by environment, combine it with the [directory adapter](/docs/adapters/directory). # TOML adapter (https://zod-config.alexandremarques.io/docs/adapters/toml) Loads the configuration from a `toml` file. ## Install [#install] This adapter needs the `smol-toml` peer dependency, if you don't have it already: ```package-install smol-toml ``` The TOML adapter is synchronous, so it also works with [`loadConfigSync`](/docs/guides/sync-loading). ## Usage [#usage] ```ts twoslash 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_/, }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `path` | `string` | Path to the TOML file. Required. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # YAML adapter (https://zod-config.alexandremarques.io/docs/adapters/yaml) Loads the configuration from a `yaml` file. ## Install [#install] This adapter needs the `yaml` peer dependency, if you don't have it already: ```package-install yaml ``` The YAML adapter is synchronous, so it also works with [`loadConfigSync`](/docs/guides/sync-loading). ## Usage [#usage] ```ts twoslash 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_/, }), }); ``` ## Options [#options] | Option | Type | Description | | --- | --- | --- | | `path` | `string` | Path to the YAML file. Required. | Also accepts the [shared adapter options](/docs/adapters#shared-adapter-options): `regex`, `silent`, `keyMatching` and `transform`. # AI skills (https://zod-config.alexandremarques.io/docs/ai) Coding agents often guess an API from older training data. Give yours the current zod-config docs in one of these ways. Each one works on its own: pick the one that fits your agent. ## Agent skill [#agent-skill] The repository ships an [agent skill](https://github.com/alexmarqs/zod-config/blob/main/skills/zod-config/SKILL.md): a short `SKILL.md` that tells the agent which API to pick, how adapters and `loadEnvConfig` work, and the mistakes to avoid. Install it with the [`skills`](https://github.com/vercel-labs/skills) command-line tool, which supports Claude Code, Cursor, Codex, OpenCode and other agents: ```bash npx skills add alexmarqs/zod-config ``` It goes into your project's agent folder (for example `.claude/skills/`). Add `-g` to install it for every project. The agent loads it when a task touches zod-config. ## Context7 [#context7] [Context7](https://context7.com/alexmarqs/zod-config) indexes these docs as `/alexmarqs/zod-config`. With the Context7 MCP server connected to your agent, ask it to use that library: ```txt Add a YAML config file to this app with zod-config. use context7 /alexmarqs/zod-config ``` To connect the server, see [Context7's install guide](https://github.com/upstash/context7#installation). In Claude Code, for example: ```bash claude mcp add --transport http context7 https://mcp.context7.com/mcp ``` ## Point your agent to the docs [#point-your-agent-to-the-docs] No install: add a few lines to the file your agent reads for project instructions, such as `AGENTS.md`, `CLAUDE.md` or `.cursor/rules`: ```md title="AGENTS.md" ## zod-config This project loads its configuration with zod-config. Before writing code that uses it, read https://zod-config.alexandremarques.io/llms.txt and open the pages it links to. ``` The site serves these files for agents: | File | What it holds | | --- | --- | | [`/llms.txt`](/llms.txt) | An index of every page, with a short description and a link to its Markdown. | | [`/llms-full.txt`](/llms-full.txt) | Every page in one file. | | `/llms.mdx/docs/.md` | One page as Markdown, e.g. [`/llms.mdx/docs/env.md`](/llms.mdx/docs/env.md). | Every page also has a **Copy Markdown** button, and an **Open** menu that sends the page to ChatGPT, Claude and other assistants. # Astro (https://zod-config.alexandremarques.io/docs/env/astro) Use the root `zod-config` export with `clientPrefix: "PUBLIC_"`. ## Define the schema [#define-the-schema] ```ts title="src/env.ts" import { loadEnvConfig } from 'zod-config'; import { z } from 'zod'; export const env = loadEnvConfig({ clientPrefix: 'PUBLIC_', server: { DB_PASSWORD: z.string(), }, client: { PUBLIC_API_URL: z.url(), }, runtimeEnv: import.meta.env, }); ``` Astro exposes only `PUBLIC_`-prefixed variables to client-side code. Server code (pages, endpoints, middleware) can read every variable. ## Validate when Astro starts [#validate-when-astro-starts] To stop `astro dev` and `astro build` on a missing or invalid variable, add the [`zod-config/vite` plugin](/docs/env/vite#validate-when-vite-starts) under `vite.plugins` in `astro.config.ts`: ```ts title="astro.config.ts" import { defineConfig } from 'astro/config'; import { zodConfigEnv } from 'zod-config/vite'; export default defineConfig({ vite: { plugins: [zodConfigEnv()] }, }); ``` ## Build-time and runtime values [#build-time-and-runtime-values] Astro replaces `import.meta.env` values statically at build time. Because `server` variables are read from `runtimeEnv` first, passing the whole `import.meta.env` means a server value present in `.env` at build time wins over the one set at runtime. This matches what Astro's own `import.meta.env` does. To read server variables at runtime instead, list only the client keys in `runtimeEnv`. Server values then come from `process.env`, which most Astro adapters provide: ```ts export const env = loadEnvConfig({ clientPrefix: 'PUBLIC_', server: { DB_PASSWORD: z.string() }, client: { PUBLIC_API_URL: z.url() }, runtimeEnv: { PUBLIC_API_URL: import.meta.env.PUBLIC_API_URL, }, }); ``` For the Deno adapter, Astro's docs read variables with `Deno.env.get()` instead of `process.env`. In that case, pass the server values in `runtimeEnv` yourself. ## Astro's own `astro:env` [#astros-own-astroenv] Astro also ships `astro:env`, a schema for environment variables declared in `astro.config` with `envField`. Use it if you only need Astro. `loadEnvConfig` is useful when you want the same Zod schemas across frameworks, or Zod features `envField` does not have. ## See also [#see-also] - [Options and errors](/docs/env#options) - [Astro: Using environment variables](https://docs.astro.build/en/guides/environment-variables/) # Coming from T3 Env or similar (https://zod-config.alexandremarques.io/docs/env/from-t3-env) `loadEnvConfig` keeps the shape of T3 Env's `createEnv`: `server` and `client` objects of Zod schemas, plus `runtimeEnv`. | T3 Env | zod-config | Notes | | --- | --- | --- | | `createEnv` from `@t3-oss/env-nextjs` | `loadEnvConfig` from `zod-config/nextjs` | Prefix fixed to `NEXT_PUBLIC_`. | | `createEnv` from `@t3-oss/env-core` | `loadEnvConfig` from `zod-config` | Pass the prefix as `clientPrefix`. | | `server`, `client`, `shared` | `server`, `client`, `shared` | Unchanged. | | `runtimeEnv` | `runtimeEnv` | Works as it is. Server entries are optional (without them, server values come from `process.env`), but client entries must stay: client values are only read from `runtimeEnv`. | | `runtimeEnvStrict` (env-core) | `runtimeEnv` with `strict: true` | Every server, client and shared key must be listed. | | `onValidationError` | `onError` | Receives the Zod error rather than the issues array: use `error.issues`. Throw from it to replace the default error. | | `skipValidation` | `skipValidation` | Returns raw values. Reading server variables in the browser still throws. | | `import "./src/env"` in `next.config` | The same, or [`withZodConfigEnv`](/docs/env/nextjs#validate-when-nextjs-starts) | The wrapper also works with `next.config.mjs` and path aliases. On Vite, use the [`zodConfigEnv` plugin](/docs/env/vite#validate-when-vite-starts). | | `isServer` | `isServer` | Unchanged. | ```ts twoslash title="src/env.ts" import { loadEnvConfig } from 'zod-config/nextjs'; import { z } from 'zod'; export const env = loadEnvConfig({ server: { DATABASE_URL: z.url() }, client: { NEXT_PUBLIC_APP_URL: z.url() }, runtimeEnv: { DATABASE_URL: process.env.DATABASE_URL, NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL, }, onError: (error) => { console.error(error.issues); }, }); ``` # Type-safe environment variables (https://zod-config.alexandremarques.io/docs/env) Validate environment variables with Zod in apps that have a browser bundle, such as Next.js, Vite, Astro and TanStack Start. `loadEnvConfig` gives you: - separate `server` and `client` schemas, plus `shared` for variables read on both sides, such as `NODE_ENV`; - public prefix enforcement: client keys must start with the framework's public prefix, server keys must not; - protection against reading server variables in the browser. You write one env file. It is validated, synchronously, the first time it is imported. Next.js and Vite also get an optional helper that validates it when the dev server or the build starts. ## Entry points [#entry-points] | Import | Exports | Notes | | --- | --- | --- | | `zod-config/nextjs` | `loadEnvConfig` | Prefix fixed to `NEXT_PUBLIC_`. `runtimeEnv` needs one entry per `client` and `shared` key, checked by the types. | | `zod-config` | `loadEnvConfig` | Pass the prefix as `clientPrefix`, e.g. `"VITE_"` or `"PUBLIC_"`. `runtimeEnv` can be any object, e.g. `import.meta.env`. | | `zod-config/nextjs/config` | `withZodConfigEnv` | Node.js only. Validates the env file when Next.js reads its config. | | `zod-config/vite` | `zodConfigEnv` | Vite plugin. Validates the env file when `vite dev` or `vite build` starts. | ```ts twoslash import { z } from 'zod'; import { loadEnvConfig } from 'zod-config'; export const env = loadEnvConfig({ clientPrefix: 'PUBLIC_', server: { DATABASE_URL: z.url(), }, client: { PUBLIC_API_URL: z.url(), }, shared: { NODE_ENV: z.enum(['development', 'test', 'production']), }, runtimeEnv: { PUBLIC_API_URL: process.env.PUBLIC_API_URL, NODE_ENV: process.env.NODE_ENV, }, }); env.DATABASE_URL; // ^? ``` ## Where values come from [#where-values-come-from] - **`server` variables** are read from `runtimeEnv` first, then `process.env`, and only on the server. In the browser they are never read, and accessing one throws. - **`client` variables** are read from `runtimeEnv` only, on the server and in the browser. - **`shared` variables** are read like `server` variables on the server, and from `runtimeEnv` in the browser. They don't need the public prefix. The server is detected with `typeof window === "undefined"`. Override it with `isServer`, e.g. in jsdom tests. ### Why `runtimeEnv`? [#why-runtimeenv] In the browser there is no `process.env` to read from. Bundlers put public values in the code themselves: Next.js replaces each `process.env.NEXT_PUBLIC_*` that the code writes out in full, and Vite puts them on `import.meta.env`, which only exists in your app's files. So your env file has to hand them over. Server values are read from `process.env` and don't need to be listed. ## When validation runs [#when-validation-runs] The environment is validated when the file that calls `loadEnvConfig` is first imported. In a single-page app, that is in the browser, when the app loads. To fail as soon as the dev server or the build starts: | Framework | How | | --- | --- | | Next.js | Import the env file in `next.config.ts`, or wrap the config with [`withZodConfigEnv`](/docs/env/nextjs#validate-when-nextjs-starts) | | Vite, TanStack Start, Astro | Add the [`zodConfigEnv` plugin](/docs/env/vite#validate-when-vite-starts) | The plugin and the wrapper find `env.ts` (or `env.mts`, `env.js`, …) in `src/`, then in the project root, and run it with [jiti](https://github.com/unjs/jiti). If the file is somewhere else, pass its path: ```ts zodConfigEnv({ file: 'config/env.ts' }); withZodConfigEnv(nextConfig, { file: 'config/env.ts' }); ``` ### What to know about the env file [#what-to-know-about-the-env-file] - **It runs in Node.js** when the plugin or the wrapper loads it. Keep it to the schema and `loadEnvConfig`: an import such as `server-only`, or code that needs the browser, fails there. - **jiti** is an optional peer dependency, version 2 or later. Path aliases from `tsconfig.json` need jiti 2.7 or later, and only the root `tsconfig.json` is read, not files it references such as `tsconfig.app.json`. On Vite, `resolve.alias` works too. - **Vite restarts** the dev server when `env.ts` or a `.env` file changes, not when a file that `env.ts` imports changes. ## Errors [#errors] An invalid environment throws an `Error` that lists each invalid variable and why: ```txt Error: Invalid environment variables: DATABASE_URL: Invalid input: expected string, received undefined PORT: Invalid input: expected number, received NaN ``` Misconfiguration also throws, before any validation: a `client` key without the prefix, a `server` key with it, the same key in two groups, `client` or `shared` keys without `runtimeEnv` or (on `zod-config`) `client` keys without `clientPrefix`, or no keys at all. ## Options [#options] | Option | Description | | --- | --- | | `server`, `client` | Objects of Zod schemas. At least one group is required. | | `shared` | Variables read on the server and in the browser, without the public prefix, e.g. `NODE_ENV`. In the browser they come from `runtimeEnv`: list them on Next.js (`NODE_ENV: process.env.NODE_ENV`), or add them next to `import.meta.env` on Vite (`runtimeEnv: { ...import.meta.env, NODE_ENV: process.env.NODE_ENV }`). | | `clientPrefix` | `zod-config` only. Required and non-empty when `client` has keys. | | `runtimeEnv` | Where values come from. Required when `client` or `shared` has keys. With `zod-config/nextjs`, list each client and shared key as `process.env.NAME`; server keys are optional. On the server, entries take priority over `process.env`, which provides the rest. | | `onError` | `(error) => void`, called with the Zod error (use `error.issues`) before the `Error` above is thrown. Throw from it to replace that error. Unlike `loadConfig`'s `onError`, it does not swallow the failure. | | `skipValidation` | Return raw values without running Zod, e.g. `skipValidation: process.env.SKIP_ENV_VALIDATION === "true"` when secrets are not available while building. Defaults, coercion and transforms are not applied, so the inferred types may not match the values. Reading server variables in the browser still throws. | | `isServer` | Override server detection (default `typeof window === "undefined"`), e.g. in jsdom tests. | | `strict` | `zod-config` only. Type-checks that `runtimeEnv` lists every `server`, `client` and `shared` key and, when written inline, no undeclared key. For bundlers that only inline variables written out in full (e.g. `process.env.EXPO_PUBLIC_API_URL` in Expo). Type-level only. | ## When not to use it [#when-not-to-use-it] `loadEnvConfig` is for apps with a browser bundle. For a server without one, use [`loadConfig`](/docs) or [`loadConfigSync`](/docs/guides/sync-loading) with the [env adapter](/docs/adapters/env), or any other adapter. SvelteKit 3 is not supported: it has its own `$app/env` module and reserves `src/env.ts`. # Next.js (https://zod-config.alexandremarques.io/docs/env/nextjs) `zod-config/nextjs` fixes the client prefix to `NEXT_PUBLIC_`. ## Define the schema [#define-the-schema] ```ts twoslash title="src/env.ts" import { loadEnvConfig } from 'zod-config/nextjs'; import { z } from 'zod'; export const env = loadEnvConfig({ // server-only, read from process.env server: { DATABASE_URL: z.url(), // Zod 3: z.string().url() PORT: z.coerce.number().default(3000), }, // available in the browser, keys must start with NEXT_PUBLIC_ client: { NEXT_PUBLIC_APP_URL: z.url(), }, // read on both sides, without the prefix shared: { NODE_ENV: z.enum(['development', 'test', 'production']), }, // one entry per client and shared key, so Next.js can inline the values runtimeEnv: { NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL, NODE_ENV: process.env.NODE_ENV, }, }); ``` `runtimeEnv` needs one entry per `client` and `shared` key, written as `process.env.NAME`: Next.js only inlines a variable into the browser bundle where the code writes it out in full. The types check that every one is listed. ## Use it [#use-it] ```ts import { env } from '@/env'; env.PORT; // number env.NEXT_PUBLIC_APP_URL; // string, on the server and in the browser env.DATABASE_URL; // string on the server, throws in the browser ``` An invalid environment throws an `Error` that lists each invalid variable and why. See [errors and options](/docs/env#errors). ## Validate when Next.js starts [#validate-when-nextjs-starts] By default, `env.ts` is checked the first time it is imported, so `next dev` starts even with a missing variable and only fails when a page uses it. To check it when `next dev` or `next build` starts, choose **one** of these options. With `next.config.ts` and no path aliases such as `@/` in `env.ts`. Nothing to install. ```ts title="next.config.ts" import './src/env'; import type { NextConfig } from 'next'; const nextConfig: NextConfig = {}; export default nextConfig; ``` With `next.config.js` / `.mjs`, or path aliases in `env.ts`. The wrapper finds `env.ts` in `src/` or the project root, runs it with [jiti](https://github.com/unjs/jiti), and returns your config unchanged. Path aliases come from the `paths` of `tsconfig.json`. ```ts twoslash title="next.config.mjs" import { withZodConfigEnv } from 'zod-config/nextjs/config'; export default withZodConfigEnv({ // your Next.js config }); ``` For the same cases as the wrapper, without it. ```ts title="next.config.mjs" import { createJiti } from 'jiti'; await createJiti(import.meta.url, { tsconfigPaths: true }).import('./src/env.ts'); export default { // your Next.js config }; ``` - `next build` fails before compiling, with the same `Invalid environment variables` message. - `next dev` reports the error and exits at startup. - Values from `.env` files work: Next.js loads them before reading the config. - It works together with [`skipValidation`](#building-without-secrets): with `SKIP_ENV_VALIDATION=true`, the build still runs. To use the wrapper or jiti by hand, install `jiti` as a regular dependency, since `next start` needs it too: ```package-install jiti ``` ### Deploying [#deploying] `next start` reads `next.config` too, so with any of the three options it validates again at start, and `env.ts` (plus `jiti`, for the wrapper) must be among the deployed files. With `output: "standalone"`, the server does not read `next.config` at start: it needs neither, and the environment is validated on the first request that imports `env.ts`. ### Monorepos [#monorepos] The wrapper looks for `env.ts` from the working directory. When you run `next build apps/web` from the repository root, pass an absolute path: ```ts twoslash title="apps/web/next.config.mjs" import { fileURLToPath } from 'node:url'; import { withZodConfigEnv } from 'zod-config/nextjs/config'; export default withZodConfigEnv( {}, { file: fileURLToPath(new URL('./src/env.ts', import.meta.url)) }, ); ``` jiti and `tsconfig.json` are then taken from the package that holds that file. ## Building without secrets [#building-without-secrets] When secrets are not available during `next build`, skip validation for the build: ```bash SKIP_ENV_VALIDATION=true next build ``` ```ts export const env = loadEnvConfig({ // ... skipValidation: process.env.SKIP_ENV_VALIDATION === 'true', }); ``` With `skipValidation`, raw values are returned without validation, coercion, transforms or defaults. The inferred types still describe the validated output, so they may not match the values. Render pages that read these secrets at request time, for example with `await connection()` from `next/server`. Next.js renders static pages once, during `next build`. With validation skipped, a static page that reads a missing secret saves `undefined` into its HTML, and no error is shown. ## See also [#see-also] - [Coming from T3 Env or similar](/docs/env/from-t3-env) - [Next.js: Environment variables](https://nextjs.org/docs/app/guides/environment-variables) # TanStack Start (https://zod-config.alexandremarques.io/docs/env/tanstack-start) TanStack Start builds with Vite, so use the root `zod-config` export with `clientPrefix: "VITE_"`. ## Define the schema [#define-the-schema] ```ts title="src/env.ts" import { loadEnvConfig } from 'zod-config'; import { z } from 'zod'; export const env = loadEnvConfig({ clientPrefix: 'VITE_', server: { DATABASE_URL: z.url(), }, client: { VITE_APP_NAME: z.string(), }, runtimeEnv: import.meta.env, }); ``` Client code can only read `VITE_`-prefixed variables. On the server, `server` variables are read from `runtimeEnv` first, then `process.env`. TanStack Start loads your `.env` files automatically. ## Validate when Vite starts [#validate-when-vite-starts] By default, the environment is validated when `env.ts` is first imported. To stop `vite dev` and `vite build` on a missing or invalid variable, add the [`zodConfigEnv` plugin](/docs/env/vite#validate-when-vite-starts) to `vite.config.ts`: ```ts title="vite.config.ts" import { tanstackStart } from '@tanstack/react-start/plugin/vite'; import { defineConfig } from 'vite'; import { zodConfigEnv } from 'zod-config/vite'; export default defineConfig({ plugins: [zodConfigEnv(), tanstackStart()], }); ``` ## Read server variables in server functions [#read-server-variables-in-server-functions] Read `server` variables inside `createServerFn` handlers (or server routes and middleware). Route loaders also run in the browser, where server values are never available, so reading one there throws. ```ts import { createServerFn } from '@tanstack/react-start'; import { env } from './env'; export const getUsers = createServerFn().handler(async () => { const db = connect(env.DATABASE_URL); // your database client; runs on the server only return db.users.findMany(); }); ``` A loader that needs server data calls the server function. ## Runtimes that inject variables per request [#runtimes-that-inject-variables-per-request] `loadEnvConfig` reads the environment once, when `env.ts` is first imported. On runtimes that inject variables per request, such as Cloudflare Workers, TanStack Start's docs recommend reading `process.env` inside each handler instead of at module scope. Check how your deployment target provides variables before relying on a module-level `env`. ## See also [#see-also] - [Options and errors](/docs/env#options) - [TanStack Start: Environment variables](https://tanstack.com/start/latest/docs/framework/react/guide/environment-variables) # Vite (https://zod-config.alexandremarques.io/docs/env/vite) Use the root `zod-config` export with `clientPrefix: "VITE_"` and pass `import.meta.env` as `runtimeEnv`. ## Define the schema [#define-the-schema] ```ts title="src/env.ts" import { loadEnvConfig } from 'zod-config'; import { z } from 'zod'; export const env = loadEnvConfig({ clientPrefix: 'VITE_', client: { VITE_API_URL: z.url(), VITE_SENTRY_DSN: z.string().optional(), }, runtimeEnv: import.meta.env, }); ``` ```ts import { env } from './env'; env.VITE_API_URL; // string ``` Vite exposes only `VITE_`-prefixed variables to client code, on `import.meta.env`, and replaces them statically at build time. Vite's [`envPrefix`](https://vite.dev/config/shared-options#envprefix) option changes the prefix; if you change it, pass the same value as `clientPrefix`. ## Validate when Vite starts [#validate-when-vite-starts] In a single-page app, `env.ts` runs in the browser, so validation happens when the app loads, not at build. To stop `vite dev` and `vite build` on a missing or invalid variable instead, add the `zodConfigEnv` plugin. It finds `env.ts` in `src/` or the project root and runs it with [jiti](https://github.com/unjs/jiti), so install `jiti` if you don't have it already: ```package-install -D jiti ``` ```ts twoslash title="vite.config.ts" import { defineConfig } from 'vite'; import { zodConfigEnv } from 'zod-config/vite'; export default defineConfig({ plugins: [zodConfigEnv()], }); ``` - The command stops before anything is built, with the same `Invalid environment variables` message. - While the plugin runs `env.ts`, `import.meta.env` holds the values the way Vite reads them: the `.env` files of the current mode, then `process.env`, plus Vite's `MODE`, `DEV`, `PROD` and `BASE_URL`. - Path aliases come from `resolve.alias` in the Vite config, or the `paths` of `tsconfig.json`. - The dev server restarts when `env.ts` changes, and checks it again. - The plugin only validates. It does not change the bundle: Vite still decides which variables reach the browser. - It does nothing under Vitest or `vite preview`, so a test run does not need every variable. - It works with Vite 5 and later, and with frameworks built on Vite, such as [TanStack Start](/docs/env/tanstack-start) and [Astro](/docs/env/astro). - The file is somewhere else? Pass its path, from the Vite root: `zodConfigEnv({ file: 'config/env.ts' })`. With server-side rendering, add a `server` schema. On the server, `server` variables are read from `runtimeEnv` first, then `process.env`. In the browser they are never read, and accessing one throws. ## Types for import.meta.env [#types-for-importmetaenv] `loadEnvConfig` returns typed values on its own. If you also read `import.meta.env` directly, declare your variables in `src/vite-env.d.ts` as the Vite docs describe: ```ts title="src/vite-env.d.ts" interface ImportMetaEnv { readonly VITE_API_URL: string; } interface ImportMeta { readonly env: ImportMetaEnv; } ``` ## See also [#see-also] - [Options and errors](/docs/env#options) - [Vite: Env variables and modes](https://vite.dev/guide/env-and-mode) # Callbacks (https://zod-config.alexandremarques.io/docs/guides/callbacks) Use `onSuccess` and `onError` to react to the result of loading, for example when you don't `await` the promise. ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); loadConfig({ schema: schemaConfig, onError: (error) => { console.error('An error occurred while loading the configuration:', error); }, onSuccess: (config) => { console.log('Configuration loaded successfully:', config); }, }); ``` `onError` receives the Zod error. When you pass it, the validation error is handled by your callback instead of being thrown. # Combine multiple adapters (https://zod-config.alexandremarques.io/docs/guides/combine-adapters) You can combine multiple adapters to load the configuration from different sources. Zod Config **deeply merges the configuration from the different sources, following the order of the adapters**: later adapters override earlier ones. ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; import { jsonAdapter } from 'zod-config/json-adapter'; import path from 'path'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const filePath = path.join(__dirname, 'config.json'); const config = await loadConfig({ schema: schemaConfig, adapters: [ jsonAdapter({ path: filePath }), envAdapter(), // overrides values from config.json ], }); ``` When combining multiple adapters, `null` values from later adapters override existing values. You can use this on purpose to reset a value. If one adapter fails, the data from the others is still used, and a warning is logged. See [Silent mode](/docs/guides/silent-mode). # Custom logger (https://zod-config.alexandremarques.io/docs/guides/custom-logger) Zod Config logs a warning when an adapter fails. By default it uses `console`. Pass a `logger` to send these messages somewhere else: ```ts twoslash import { z } from 'zod'; import { loadConfig, type Logger } from 'zod-config'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const customLogger: Logger = { warn: (message) => { // your custom implementation, e.g., log to a file or call an external service }, }; const config = await loadConfig({ schema: schemaConfig, logger: customLogger, }); ``` To turn the warnings off instead, use [silent mode](/docs/guides/silent-mode). # Guides (https://zod-config.alexandremarques.io/docs/guides) # Lenient key matching (https://zod-config.alexandremarques.io/docs/guides/lenient-key-matching) If your sources use a different casing or format than your schema, enable `keyMatching: 'lenient'`. This helps with environment variables, which usually use `UPPER_SNAKE_CASE`, and with systems that use other naming conventions. By default, key matching is `strict`: keys must match exactly. ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; const schemaConfig = z.object({ myHost: z.string(), }); const config = await loadConfig({ schema: schemaConfig, keyMatching: 'lenient', adapters: envAdapter({ // keyMatching: 'lenient' --> it can also be applied to the adapter level if you want to use a different key matching for a specific adapter }), }); ``` In this example, the key `MYHOST`, `MY_HOST` or `my-host` from the adapter is matched to `myHost` in your schema. Lenient matching compares keys after: 1. removing all non-alphanumeric characters (like underscores, hyphens and dots); 2. converting them to lowercase. # Load once (https://zod-config.alexandremarques.io/docs/guides/load-once) `loadConfig` is stateless: it reads every configured source on each call. Caching is left to you. With remote sources such as AWS Secrets Manager or SSM, load the config once and reuse the result instead of calling `loadConfig` per request. If all your adapters are synchronous, call [`loadConfigSync`](/docs/guides/sync-loading) once at module scope and export the result. ## Top-level await [#top-level-await] With ES modules, the simplest option is to export the result of a top-level `await loadConfig(...)` from a module such as `config.ts`. It loads once on first import (in AWS Lambda, during the init phase). Startup fails when the schema rejects the result. An adapter read error is only a warning: `loadConfig` continues with empty data from that adapter, so a schema of optional fields or defaults still starts. ## Load on first use [#load-on-first-use] To defer loading until the config is first needed, cache the load promise (add a TTL yourself if needed): ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { awsSecretsManagerAdapter } from 'zod-config/aws-secrets-manager-adapter'; const schema = z.object({ DB_HOST: z.string(), DB_PASSWORD: z.string() }); let configPromise: Promise> | undefined; export const getConfig = () => { configPromise ??= loadConfig({ schema, adapters: awsSecretsManagerAdapter({ secretId: 'my-app/config' }), }).catch((error) => { configPromise = undefined; // cleared only when loadConfig throws throw error; }); return configPromise; }; export const handler = async () => { const config = await getConfig(); // ... }; ``` The `.catch` runs only when `loadConfig` throws. Required fields with no defaults do that after an empty read, so the next call tries AWS again. If every field is optional or has a default, validation succeeds and those defaults stay cached until the process restarts. Leave out `onError` here: it swallows the validation error, so the cache is kept. # Silent mode (https://zod-config.alexandremarques.io/docs/guides/silent-mode) If an adapter fails, Zod Config still returns the data from the other adapters, and by default it logs a warning. Set `silent` to skip the warning, for example when a source is optional: ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const config = await loadConfig({ schema: schemaConfig, // silent: true --> also available in the global config in case you want to use it for all adapters adapters: envAdapter({ silent: true }), }); ``` `silent` can be set on one adapter or globally on `loadConfig`. The adapter-level value takes precedence. # Synchronous loading (https://zod-config.alexandremarques.io/docs/guides/sync-loading) `loadConfig` is asynchronous to allow for asynchronous adapters. If you only use synchronous adapters, use `loadConfigSync`, which returns the configuration directly instead of a promise. These built-in adapters are synchronous and work with `loadConfigSync`: - [`envAdapter`](/docs/adapters/env) - [`jsonAdapter`](/docs/adapters/json) - [`json5Adapter`](/docs/adapters/json5) - [`yamlAdapter`](/docs/adapters/yaml) - [`tomlAdapter`](/docs/adapters/toml) - [`dotEnvAdapter`](/docs/adapters/dotenv) When you [write your own adapter](/docs/adapters/custom) for `loadConfigSync`, implement the `SyncAdapter` type instead of `Adapter`. The schema must be synchronous too (no async refinements or transforms). ```ts twoslash import { z } from 'zod'; import { loadConfigSync } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; import { jsonAdapter } from 'zod-config/json-adapter'; import path from 'path'; const schemaConfig = z.object({ port: z.string().regex(/^\d+$/), host: z.string(), }); const filePath = path.join(__dirname, 'config.json'); const config = loadConfigSync({ schema: schemaConfig, adapters: [jsonAdapter({ path: filePath }), envAdapter()], }); ``` # Transform (https://zod-config.alexandremarques.io/docs/guides/transform) The `transform` option modifies key-value pairs before the schema processes them. Use it to normalize data, filter out unwanted keys or change values. The function receives an object with `key` and `value`, and returns either a transformed object or `false` to drop the pair. `transform` can be set globally (all adapters) or on one adapter. When both are set, the adapter-level transform takes precedence. `transform` is the first step of the processing pipeline: it runs before key matching, the nesting separator and the other features. ```ts twoslash import { z } from 'zod'; import { loadConfig } from 'zod-config'; import { envAdapter } from 'zod-config/env-adapter'; const schema = z.object({ database: z.object({ host: z.string(), port: z.string(), }), apiKey: z.string(), }); // Global transform - applied to all adapters const config = await loadConfig({ schema, transform: ({ key, value }) => { // Drop sensitive keys if (key.includes('SECRET')) { return false; } // Transform keys to lowercase return { key: key.toLowerCase(), value, }; }, adapters: envAdapter({ customEnv: { DATABASE_HOST: 'localhost', DATABASE_PORT: '5432', API_KEY: 'my-key', SECRET_TOKEN: 'should-be-dropped', }, nestingSeparator: '_', }), }); // Adapter-level transform - applied only to this adapter const configWithAdapterTransform = await loadConfig({ schema, adapters: envAdapter({ customEnv: { MY_APP_DATABASE_HOST: 'localhost', MY_APP_DATABASE_PORT: '5432', MY_APP_API_KEY: 'my-key', OTHER_VAR: 'ignored', }, transform: ({ key, value }) => { // Only process keys that start with 'MY_APP_' if (!key.startsWith('MY_APP_')) { return false; } // Remove the prefix and convert to lowercase const cleanKey = key.replace(/^MY_APP_/, '').toLowerCase(); return { key: cleanKey, value, }; }, nestingSeparator: '_', }), }); // Complex transformation with multiple operations const complexConfig = await loadConfig({ schema: z.object({ api: z.object({ key: z.string(), timeout: z.string(), }), database: z.object({ host: z.string(), port: z.string(), }), }), adapters: envAdapter({ customEnv: { API_KEY: 'secret123', API_TIMEOUT: '30000', DB_HOST: 'localhost', DB_PORT: '5432', CACHE_TTL: '3600', }, transform: ({ key, value }) => { // Transform different prefixes to nested structure if (key.startsWith('API_')) { return { key: key.replace('API_', 'api.').toLowerCase(), value, }; } if (key.startsWith('DB_')) { return { key: key.replace('DB_', 'database.').toLowerCase(), value, }; } // Drop other keys return false; }, nestingSeparator: '.', }), }); ``` # Getting started (https://zod-config.alexandremarques.io/docs) Zod Config loads configuration from one or more sources (environment variables, files, AWS, your own) and validates it with a [Zod](https://zod.dev) schema, so the result is fully typed. ## Install [#install] ```package-install zod-config zod ``` ## Quick start [#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 options but returns the result directly, without a promise. `loadConfigSync` only supports synchronous adapters and schemas. See [Synchronous loading](/docs/guides/sync-loading). By default, Zod Config loads the configuration from `process.env`, so you don't need to provide any adapter: ```ts twoslash 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); // ^? ``` To read from other sources, pass one or more [adapters](/docs/adapters). Built-in adapters are imported from `zod-config/`: ```ts twoslash import { z } from 'zod'; 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()], }); ``` ## Options [#options] The 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(s) to load the configuration from. If not provided, `process.env` is used. | ❌ | N/A | N/A | | `onError` | `(error: InferredErrorConfig) => void` | A callback called when an error occurs. See [Callbacks](/docs/guides/callbacks). | ❌ | ✅ | ❌ | | `onSuccess` | `(data: InferredDataConfig) => void` | A callback called when the configuration is loaded successfully. | ❌ | ✅ | ❌ | | `logger` | `Logger` | A custom logger used to log messages. Defaults to `console`. See [Custom logger](/docs/guides/custom-logger). | ❌ | ✅ | ❌ | | `keyMatching` | `'strict' \| 'lenient'` | How to match keys between the schema and the adapters' data. Defaults to `strict`. See [Lenient key matching](/docs/guides/lenient-key-matching). | ❌ | ✅ | ✅ | | `silent` | `boolean` | Whether to suppress errors. Defaults to `false`. See [Silent mode](/docs/guides/silent-mode). | ❌ | ✅ | ✅ | | `transform` | `(obj: { key: string; value: unknown }) => { key: string; value: unknown } \| false` | Transforms key-value pairs before processing. Returning `false` drops the pair. See [Transform](/docs/guides/transform). | ❌ | ✅ | ✅ | Options marked as both "Global" and "Adapter" can be set at the global level (affecting all adapters) or on an individual adapter (affecting only that adapter). When both are set, the adapter-level option takes precedence. Adapter-specific options are listed on each [adapter's page](/docs/adapters). The package also exports the types you need to [write your own adapters](/docs/adapters/custom). Some options are shared between the global config and the adapter config, so your adapters can accept them too. ## Compatibility [#compatibility] Zod Config supports both [Zod 4](https://zod.dev/v4) and [Zod 3](https://v3.zod.dev/) out of the box. Make sure you have `zod-config@^1.0.0` and `zod@^3.25.1` or `zod@^4.0.0`. Zod 3 support is deprecated and will be removed in the next major version. Use Zod 4 or Zod 4 Mini for new code. ```ts // 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'; ```