{"id":13903226,"url":"https://github.com/alexmarqs/zod-config","last_synced_at":"2025-04-05T18:04:59.306Z","repository":{"id":219603214,"uuid":"738172680","full_name":"alexmarqs/zod-config","owner":"alexmarqs","description":"Load configuration variables from multiple sources with flexible adapters, ensuring type safety with Zod.","archived":false,"fork":false,"pushed_at":"2025-03-20T17:10:17.000Z","size":333,"stargazers_count":80,"open_issues_count":6,"forks_count":8,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-29T17:02:12.055Z","etag":null,"topics":["adapters","config","directory","dotenv","environment-variables","files","json","typesafe","typescipt","typescript","zod"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/zod-config","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alexmarqs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-02T15:46:08.000Z","updated_at":"2025-03-28T21:19:40.000Z","dependencies_parsed_at":"2025-02-22T10:21:46.962Z","dependency_job_id":"b9bcd503-dab6-45c1-bcd0-9099664a7158","html_url":"https://github.com/alexmarqs/zod-config","commit_stats":null,"previous_names":["alexmarqs/zod-config"],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexmarqs%2Fzod-config","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexmarqs%2Fzod-config/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexmarqs%2Fzod-config/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alexmarqs%2Fzod-config/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alexmarqs","download_url":"https://codeload.github.com/alexmarqs/zod-config/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247378135,"owners_count":20929296,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["adapters","config","directory","dotenv","environment-variables","files","json","typesafe","typescipt","typescript","zod"],"created_at":"2024-08-06T22:01:53.290Z","updated_at":"2025-04-05T18:04:59.275Z","avatar_url":"https://github.com/alexmarqs.png","language":"TypeScript","funding_links":[],"categories":["typescript"],"sub_categories":[],"readme":"\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/alexmarqs/zod-config/blob/main/.github/assets/logo.png?raw=true\" width=\"200px\" align=\"center\" alt=\"Zod logo\" /\u003e\n  \u003ch1 align=\"center\"\u003eZod Config\u003c/h1\u003e\n  \u003cp align=\"center\"\u003e\n   Load configuration variables from multiple sources type safely using Zod.\n  \u003c/p\u003e\n\u003c/p\u003e\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/alexmarqs/zod-config/actions/workflows/ci-cd.yaml\" target=\"_blank\"\u003e\u003cimg height=20 src=\"https://github.com/alexmarqs/zod-config/actions/workflows/ci-cd.yaml/badge.svg\" /\u003e\u003c/a\u003e\n  \u003ca href=\"https://opensource.org/licenses/MIT\" target=\"_blank\"\u003e\u003cimg height=20 src=\"https://img.shields.io/badge/License-MIT-yellow.svg\" /\u003e\u003c/a\u003e\n   \u003ca href=\"https://www.npmjs.com/package/zod-config\" target=\"_blank\"\u003e\u003cimg height=20 src=\"https://img.shields.io/npm/dt/zod-config.svg\" /\u003e\u003c/a\u003e\n\u003c/a\u003e\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/zod-config\" target=\"_blank\"\u003eNPM\u003c/a\u003e\n\u003c/a\u003e\n\u003c/p\u003e\n\n## Features\n\n- 👮‍♂️ **Type safety**. Zod Config uses [Zod](https://zod.dev/);\n- 🤌 **Tiny**. Zod Config is a tiny library with no dependencies, tree-shaking friendly;\n- ✨ **Flexible**. [Combine multiple adapters](#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;\n- 🪴 **Easy to use**. Zod Config is designed to be easy to use, with a simple API;\n\n\n## Install\n\n```bash\nnpm install zod-config zod # npm\npnpm add zod-config zod # pnpm\nyarn add zod-config zod # yarn\n```\n(You need to install Zod as well, if you don't have it already)\n\n\n## Table of contents:\n\n- [Quick Start](#quick-start)\n- [Default Adapter](#default-adapter)\n- [Built In Adapters](#built-in-adapters)\n  - [Env Adapter](#env-adapter)\n  - [JSON Adapter](#json-adapter)\n  - [YAML Adapter](#yaml-adapter)\n  - [TOML Adapter](#toml-adapter)\n  - [Dotenv Adapter](#dotenv-adapter)\n  - [Script Adapter](#script-adapter)\n  - [Directory Adapter](#directory-adapter)\n- [Combine multiple adapters](#combine-multiple-adapters)\n- [Callbacks](#callbacks)\n- [Custom Logger](#custom-logger)\n- [Silent mode](#silent-mode)\n- [Contributing notes](#contributing-notes)\n- [On the web](#on-the-web)\n\n\n## Quick Start\n\nZod Config provides a `loadConfig` function that takes a Zod Object schema and returns a promise that resolves to the configuration object.\n\n| Property | Type | Description | Required |\n| --- | --- | --- | --- |\n| `schema` | `AnyZodObject` | A Zod Object schema to validate the configuration. | `true` |\n| `adapters` | `Adapter[] or Adapter` | Adapter(s) to load the configuration from. If not provided, process.env will be used. | `false` |\n| `onError` | `(error: Error) =\u003e void` | A callback to be called when an error occurs. | `false` |\n| `onSuccess` | `(config: z.infer ) =\u003e void` | A callback to be called when the configuration is loaded successfully. | `false` |\n| `logger` | `Logger` | A custom logger to be used to log messages. By default, it uses `console`. | `false` |\n\nFrom the package we also expose the types `Adapter`, `Config` and `Logger` in case you want to use them in your own adapters.\n\nThis library provides some built in adapters to load the configuration from different sources via modules. You can easily import them from `zod-config/\u003cbuilt-in-adapter-module-name\u003e` (see the examples below).\n\n### Default Adapter\n\nBy default, Zod Config will load the configuration from `process.env`, no need to provide any adapter.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst config = await loadConfig({\n  schema: schemaConfig\n});\n\n// config is now type safe!\nconsole.log(config.port)\nconsole.log(config.host)\n```\n\n### Built In Adapters\n\n#### Env Adapter\n\nLoads the configuration from `process.env` or a custom object, allowing filtering the keys using a regex.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { envAdapter } from 'zod-config/env-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\n// using default env (process.env)\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: envAdapter(),\n});\n\n// using custom env + filter regex\nconst customConfig = await loadConfig({\n  schema: schemaConfig,\n  adapters: envAdapter({ \n    regex: /^MY_APP_/,\n    customEnv: {\n      MY_APP_PORT: '3000',\n      MY_APP_HOST: 'localhost',\n      IGNORED_KEY: 'ignored',\n    }})\n});\n```\n\n#### JSON Adapter\n\nLoads the configuration from a `json` file.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { jsonAdapter } from 'zod-config/json-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst filePath = path.join(__dirname, 'config.json');\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: jsonAdapter({ path: filePath }),\n});\n\n// using filter regex\nconst customConfig = await loadConfig({\n  schema: schemaConfig,\n  adapters: jsonAdapter({ \n    path: filePath,\n    regex: /^MY_APP_/,\n  }),\n});\n```\n\n#### YAML Adapter\n\nLoads 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.\n\n```bash\nnpm install yaml\n```\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { yamlAdapter } from 'zod-config/yaml-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst filePath = path.join(__dirname, 'config.yaml');\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: yamlAdapter({ path: filePath }),\n});\n\n// using filter regex\nconst customConfig = await loadConfig({\n  schema: schemaConfig,\n  adapters: yamlAdapter({ \n    path: filePath,\n    regex: /^MY_APP_/,\n  }),\n});\n```\n\n#### TOML Adapter\n\nLoads 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.\n\n```bash\nnpm install smol-toml\n```\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { tomlAdapter } from 'zod-config/toml-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst filePath = path.join(__dirname, 'config.toml');\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: tomlAdapter({ path: filePath }),\n});\n\n// using filter regex\nconst customConfig = await loadConfig({\n  schema: schemaConfig,\n  adapters: tomlAdapter({ \n    path: filePath,\n    regex: /^MY_APP_/,\n  }),\n});\n```\n\n#### Dotenv Adapter\n\nLoads 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.\n\n```bash\nnpm install dotenv\n```\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { dotEnvAdapter } from 'zod-config/dotenv-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst filePath = path.join(__dirname, '.env');\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: dotEnvAdapter({ path: filePath }),\n});\n\n// using filter regex\nconst customConfig = await loadConfig({\n  schema: schemaConfig,\n  adapters: dotEnvAdapter({ \n    path: filePath,\n    regex: /^MY_APP_/,\n  }),\n});\n```\n\n#### Script Adapter\n\nLoads configuration from TypeScript (`.ts`), JavaScript (`.js`), or JSON (`.json`) files. The `.ts` and `.js` files must export a default object with the configuration data.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { scriptAdapter } from 'zod-config/script-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\n// config.ts might contain: export default { port: '3000', host: 'localhost' }\nconst filePath = path.join(__dirname, 'config.ts');\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: scriptAdapter({\n    path: filePath,\n  }),\n});\n```\n\n#### Directory Adapter\n\nLoads 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](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:\n\n```\ndefault.EXT\ndefault-{instance}.EXT\n{deployment}.EXT\n{deployment}-{instance}.EXT\n{short_hostname}.EXT\n{short_hostname}-{instance}.EXT\n{short_hostname}-{deployment}.EXT\n{short_hostname}-{deployment}-{instance}.EXT\n{hostname}.EXT\n{hostname}-{instance}.EXT\n{hostname}-{deployment}.EXT\n{hostname}-{deployment}-{instance}.EXT\nlocal.EXT\nlocal-{instance}.EXT\nlocal-{deployment}.EXT\nlocal-{deployment}-{instance}.EXT\n```\n\nWhere `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 variables, `hostname` is the `HOST`, `HOSTNAME` environment variables or `os.hostname()` and `short_hostname` is the first part of the hostname.\n\nThis adapter can be useful when using version control to manage different configurations for different environments.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { directoryAdapter } from 'zod-config/directory-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst directories = [path.join(__dirname, 'config-dir')];\n\nconst config = await loadConfig({\n  schema,\n  adapters: directoryAdapter({\n    paths: directories,\n    adapters: [\n      {\n        // Restrict adapter to handle only ts files\n        extensions: [\".ts\"], \n         // Use the scriptAdapter for handling .ts files\n        adapterFactory: (filePath: string) =\u003e \n          scriptAdapter({\n            path: filePath,\n          }),\n      },\n      // {\n      //  Add here other adapters for other file types if needed\n      // }\n    ],\n  }),\n});\n```\n\n### Combine multiple adapters\n\nYou can 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. \n\n\u003e ⚠️ **Warning**: When combining multiple adapters, `null` values from subsequent adapters will override existing values. This behavior can be used intentionally to reset configuration values.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { envAdapter } from 'zod-config/env-adapter';\nimport { jsonAdapter } from 'zod-config/json-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst filePath = path.join(__dirname, 'config.json');\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: [\n    jsonAdapter({ path: filePath }),\n    envAdapter(),\n  ],\n});\n```\n\n### Callbacks\n\nYou can use the callbacks to handle errors and success due to the async nature of the adapters.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\n\nloadConfig({\n  schema: schemaConfig,\n  onError: (error) =\u003e {\n    console.error('An error occurred while loading the configuration:', error);\n  },\n  onSuccess: (config) =\u003e {\n    console.log('Configuration loaded successfully:', config);\n  },\n});\n```\n\n### Custom Logger\n\nYou can provide a custom logger to be used to log messages. By default, it uses `console`.\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig, Logger } from 'zod-config';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst customLogger: Logger = {\n  warn: (message) =\u003e {\n    // your custom implementation, e.g., log to a file or call an external service\n  },\n};\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  logger: customLogger,\n});\n```\n\n### Silent mode\n\nIf any adapter fails, we will still return the data from other adapters. However, by default, we log a warning internally if an adapter fails. You can use the `silent` flag to avoid logging the warning. This is useful when you have multiple adapters and you don't want to log a warning for each adapter that fails. Example for the built-in `envAdapter`:\n\n```ts\nimport { z } from 'zod';\nimport { loadConfig } from 'zod-config';\nimport { envAdapter } from 'zod-config/env-adapter';\n\nconst schemaConfig = z.object({\n  port: z.string().regex(/^\\d+$/),\n  host: z.string(),\n});\n\nconst config = await loadConfig({\n  schema: schemaConfig,\n  adapters: envAdapter({ silent: true }),\n});\n```\n\n\n## Contributing notes\n\nThe goal is to have a helper to load configuration data from several srouces. If you have any source in mind, feel free to open a PR to add it or just open an issue to discuss it. More adapters are coming soon.\n\n\n## On the web \n\n- This library is referenced in the official Zod documentation as part of the [ecosystem](https://zod.dev/?id=ecosystem) section \"Powered by Zod\", check it out [here](https://zod.dev/?id=powered-by-zod);\n\n- This library is referenced in the [Next.js Weekly](https://nextjsweekly.com/issues/77) newsletter (Packages / Tools / Repos section);\n\n- Check related dev.to article [here](https://dev.to/alexmarqs/simplify-type-safe-configuration-from-multiple-sources-with-zod-config-28ad);\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexmarqs%2Fzod-config","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falexmarqs%2Fzod-config","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falexmarqs%2Fzod-config/lists"}