Skip to content
GitHub
logo logo

Type-safe layered configuration. Merge files and environment variables, validate with any schema, and get a runtime-checked object with full TypeScript IntelliSense.
  • Define declarative, isolated, and per-environment configuration files (.json, or other file extensions via parsers).
  • Validate your configuration with zod, or bring your preferred schema validation library.
  • Use a type-safe and runtime-checked configuration object across your app.

When using ConfigBuilder, configuration is loaded from two primary sources:

  1. File-basedDefine your configuration files.
  2. Environment variablesOverride configurations dynamically. This is useful for pre-built containers that require specific values at runtime.

Since the configuration follows a cascading approach, the final result depends on the order in which sources are added.

import { ConfigBuilder, z } from "@layerfig/config";
import { FileSource } from "@layerfig/config/sources/file";
import { EnvironmentVariableSource } from "@layerfig/config/sources/env";

const schema = z.object({
  baseURL: z.url(),
});

export const config = new ConfigBuilder({
  validate: (finalConfig) => schema.parse(finalConfig),
})
  //  1. Starts with a base configuration.
  .addSource(new FileSource("base.json"))
  // 2. Merges with the previous source if needed
  // .addSource(new FileSource("live.json"))
  // 3. Allows environment variables
  //    to override previous values (optional).
  .addSource(new EnvironmentVariableSource())
  // 4. Validates the merged configuration and
  //    returns the final, type-safe object.
  .build();