DEV Community

Alexandre Marques
Alexandre Marques

Posted on • Edited on

Simplify type-safe configuration from multiple sources with zod-config

Introduction

Have you ever found yourself writing the same configuration boilerplate code over and over in your TypeScript projects? While Zod excellently handles type validation, managing configuration from multiple sources still requires repetitive code for loading, merging, and validation. That's why I created zod-config.

Let's know more about zod-config

zod-config is a typescript library that helps you manage your configurations in a type-safe way. It integrates with zod to provide robust type checking and validation. Some of the key features:

Key Features:

  • 🔄 Combine multiple adapters to load the configuration from different sources
  • 🛡️ Deep merging of configurations from different sources, following adapter order
  • 🔌 Easy creation of custom adapters with exposed types and interfaces
  • 🎯 Callback functions for handling errors and success in async operations
  • 🚨 Built-in error handling and validation

How to use it

Installation

npm install zod-config
Enter fullscreen mode Exit fullscreen mode

Quick Start

zod-config provides a loadConfig function that takes a Zod Object schema and returns a promise that resolves to the configuration object with the correct type. To use adapters, you should provide them in the adapters property. If you don't provide any adapter, we will use a default adapter (process.env). 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> (check examples below).

For API Reference, please refer to the README.

Some examples of usage:

import { z } from 'zod';
import { loadConfig } from 'zod-config';
import { envAdapter } from 'zod-config/env-adapter';
import { jsonAdapter } from 'zod-config/json-adapter';
import { dotEnvAdapter } from 'zod-config/dotenv-adapter';

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

// 1) *** Using Default Adapter (process.env) ***
const config1 = await loadConfig({
  schema: schemaConfig
});

// 2) *** Using Env Adapter (process.env) with prefix key for filtering ***
const config2 = await loadConfig({
  schema: schemaConfig,
  adapters: envAdapter({ 
    prefixKey: 'MY_APP_',
    // customEnv: {...} // you can also provide a custom env object
});

// 3) *** Using JSON Adapter ***
const filePath = path.join(__dirname, 'config.json');

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

// 4) *** Using Dotenv Adapter (peer dep. dotenv needed) ***
const filePath = path.join(__dirname, '.env');

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

// 5) *** Combining multiple adapters ***
const config5 = await loadConfig({
  schema: schemaConfig,
  adapters: [
    jsonAdapter({ path: filePath }),
    envAdapter(),
  ],
});

// 6) *** Using callbacks *** 
loadConfig({
  schema: schemaConfig,
  onError: (error) => {
    console.error('An error occurred while loading the configuration:', error);
  },
  onSuccess: (config) => {
    console.log('Configuration loaded successfully:', config);
  },
});
Enter fullscreen mode Exit fullscreen mode

Real-World Use Cases

  • Microservices & Cloud Apps: Load defaults, manage secrets, and handle environment-specific configurations across your distributed system

  • Development Lifecycle: Seamlessly switch between dev, staging, and production environments with environment-specific settings

  • Type-Safe Validation: Catch configuration errors early with compile-time checks and runtime validation, ensuring your app starts with valid settings

Community and Ecosystem

zod-config is proudly featured in the official Zod documentation under "Powered by Zod". This recognition reflects our commitment to maintaining high-quality, type-safe tooling for the TypeScript ecosystem.

Contributing

We welcome all types of contributions:

  • 🐛 Bug reports and fixes
  • 💡 Feature suggestions
  • 📝 Documentation improvements
  • 🔧 Code enhancements

Visit our GitHub repository to get started.

Thanks for reading! If you find zod-config useful, please consider giving it a star on GitHub. ⭐

Happy coding! 🚀

Before you leave... I have a question for you!

If you reached this point, it means you are a type safety enthusiast and you are probably interested in working with modern technologies and tools!

Would you like to be part of a talented team that is helping the energy transition? We are hiring at epilot! Check out our career page or reach out to my Twitter if you have any questions.

Top comments (0)