c12 (pronounced as /siːtwelv/, like c-twelve) is a smart configuration loader.
[!NOTE] See the Migration section for upgrading from v3 to v4.
.js, .ts, .mjs, .cjs, .mts, .cts config loader with customizable import or unjs/jiti fallback..json config loader with JSON.parse and .jsonc, .json5, .yaml, .yml, .toml with unjs/confbox.config/ directory support (config dir proposal).rc config support with unjs/rc9.env support with variable interpolation and optional _FILE references resolutionpackage.json fileInstall package:
# ✨ Auto-detect
npx nypm install c12
Import:
// ESM import
import { loadConfig, watchConfig } from "c12";
// or using dynamic import
const { loadConfig, watchConfig } = await import("c12");
Load configuration:
// Get loaded config
const { config } = await loadConfig({});
// Get resolved config and extended layers
const { config, configFile, layers } = await loadConfig({});
[!NOTE] Merged
configmay share nested object references withlayers[].config, so mutatingconfigcan also mutate a layer (and vice versa). If you need to mutate the result, clone it first using a deep clone strategy that fits your config (for exampleklonaorstructuredClone):import { klona } from "klona"; const { config: _config, layers } = await loadConfig({}); const config = klona(_config);
c12 merged config sources with unjs/defu by below order:
$XDG_CONFIG_HOME or ~/.config)package.jsoncwdResolve configuration from this working directory. The default is process.cwd()
nameConfiguration base name. The default is config.
configFileConfiguration file name without extension. Default is generated from name (f.e., if name is foo, the config file will be => foo.config).
rcFileRC Config file name. Default is generated from name (name=foo => .foorc).
Set to false to disable loading RC config.
globalRcLoad RC config from the workspace directory, the user's config directory ($XDG_CONFIG_HOME or ~/.config) and the user's home directory. Only enabled when rcFile is provided. Set to false to disable this functionality.
When the same key is set in more than one of these, the workspace wins over the user config directory, which wins over the home directory.
dotenvLoads .env file when true or an options object is passed. It is disabled by default.
Supports loading multiple files that extend eachother in left-to-right order when a fileNames array of relative/absolute paths is passed in the options object.
Example:
# .env
CONNECTION_POOL_MAX="10"
DATABASE_URL="<...rds...>"
# .env.local
DATABASE_URL="<...localhost...>"
export default {
connectionPoolMax: process.env.CONNECTION_POOL_MAX,
databaseURL: process.env.DATABASE_URL,
};
import { loadConfig } from "c12";
const config = await loadConfig({
dotenv: {
fileName: [".env", ".env.local"],
},
});
console.log(config.config.connectionPoolMax); // "10"
console.log(config.config.databaseURL); // "<...localhost...>"
interpolateEnabled by default. Variables within .env files are interpolated using $VAR or ${VAR} syntax (use \${VAR} to escape). Within braces, a default value can be provided with ${VAR:-default} (used when VAR is unset or empty) or ${VAR-default} (used when VAR is unset only). Default values can themselves contain interpolations. A reference that cannot be resolved is kept as-is rather than replaced with an empty value. Set to false to disable.
# .env
BASE_DIR="/test"
# "/test/further"
ANOTHER_DIR="${BASE_DIR}/further"
# "/test/fallback" when CACHE_DIR_INPUT is unset or empty
CACHE_DIR="${CACHE_DIR_INPUT:-${BASE_DIR}/fallback}"
# "info" when LOG_LEVEL_INPUT is unset (an empty value is kept as-is)
LOG_LEVEL="${LOG_LEVEL_INPUT-info}"
# kept as the literal "${UNKNOWN}" since it cannot be resolved
UNRESOLVED="${UNKNOWN}"
expandFileReferencesDisabled by default. Environment variables ending with _FILE are resolved by reading the file at the specified path and assigning its trimmed content to the base key (without the _FILE suffix). This is useful for container secrets (e.g. Docker, Kubernetes) where sensitive values are mounted as files. Set to true to enable.
# .env
DATABASE_PASSWORD_FILE="/run/secrets/db_password"
import { loadConfig } from "c12";
const config = await loadConfig({
dotenv: {
expandFileReferences: true,
},
});
// DATABASE_PASSWORD is now set to the contents of /run/secrets/db_password
parseCustom .env file parser with (src: string) => Record<string, string> signature (exported as DotenvParseFn type). By default, node:util.parseEnv is used when available, falling back to the optional dotenv package.
import { loadConfig } from "c12";
import { parse } from "dotenv";
const config = await loadConfig({
dotenv: { parse },
});
packageJsonLoads config from nearest package.json file. It is disabled by default.
If true value is passed, c12 uses name field from package.json.
You can also pass either a string or an array of strings as a value to use those fields.
defaultsSpecify default configuration. It has the lowest priority and is applied after extending config.
defaultConfigSpecify default configuration. It is applied before extending config.
overridesSpecify override configuration. It has the highest priority and is applied before extending config.
Environment specific configuration keys in overrides are applied the same way as in config files.
omit$KeysExclude environment-specific and built-in keys start with $ in the resolved config. The default is false.
importCustom import function used to load configuration files. By default, c12 uses native import() with unjs/jiti as fallback.
Example: Using a custom jiti instance with options:
import { createJiti } from "jiti";
const jiti = createJiti(import.meta.url, {/* jiti options */});
const { config } = await loadConfig({
import: (id) => jiti.import(id),
});
jitiOptionsOptions passed to unjs/jiti when c12 falls back to it for loading config files. Has no effect if a custom import is provided.
Example:
const { config } = await loadConfig({
jitiOptions: {
fsCache: false,
transformOptions: {/* ... */},
},
});
resolveModuleCustom resolver for picking which export to use from the loaded module. Default: mod.default if the module has a default export (even when it is null or undefined), otherwise mod.
Example: Using a named export:
const { config } = await loadConfig({
resolveModule: (mod) => mod.myConfig,
});
gigetOptions passed to unjs/giget when extending layer from git source.
mergerCustom options merger function. Default is defu.
Note: Custom merge function should deeply merge options with arguments high -> low priority.
envMergerCustom merger used to apply environment specific configuration ($<envName> and $env.<envName> keys) onto the config. Defaults to merger (or defu).
Note: It only applies when merging the env keys of a layer (or of overrides) onto that same layer. Layers (extends), overrides, RC, package.json and defaults are still combined with merger.
Useful when an environment override should replace a value instead of being merged into it. For example, to replace arrays instead of concatenating them:
import { createDefu } from "defu";
const replaceArrays = createDefu((obj, key, value) => {
if (Array.isArray(value)) {
obj[key] = [...value];
return true;
}
});
const { config } = await loadConfig({
envMerger: (...sources) => replaceArrays({}, ...sources),
});
envNameEnvironment name used for environment specific configuration.
The default is process.env.NODE_ENV. You can set envName to false or an empty string to disable the feature.
You can also pass an array of names (e.g. ["production", "prerender"]) to apply several environments. Later names have higher priority.
contextContext object passed to dynamic config functions.
resolveYou can define a custom function that resolves the config.
configFileRequiredIf this option is set to true, loader fails if the main config file does not exists.
schemaA Standard Schema (zod, valibot, arktype, ...) used to validate the final config, after all layers are merged.
import { z } from "zod";
const { config } = await loadConfig({
name: "app",
schema: z.looseObject({ port: z.coerce.number().default(3000) }),
});
The validated output replaces config, so schema defaults and transforms are applied (and unknown keys may be stripped depending on your schema). On failure, an error listing all issues is thrown (raw issues are available on error.cause).
Notes:
$development, $env, ...) are passed to the schema unless omit$Keys is enabled.layers keep the raw (unvalidated) configs, and the validated config may not share references with them.watchConfig, a validation error on reload is logged and the previous config is kept.If resolved config contains a extends key, it will be used to extend the configuration.
Extending can be nested and each layer can extend from one base or more.
The final config is merged result of extended options and user options with unjs/defu.
Each item in extends is a string that can be either an absolute or relative path to the current config file pointing to a config file for extending or the directory containing the config file.
If it starts with either github:, gitlab:, bitbucket:, or https:, c12 automatically clones it.
For custom merging strategies, you can directly access each layer with layers property.
When the same layer is reached more than once (for example, two layers both extend a shared base), it is only loaded once and the first occurrence is kept. Local layers are compared by the real path of their config file, remote sources by their source string, and layers returned by a custom resolve hook by their configFile (or cwd). Options passed to a repeated reference (such as meta or overrides) are ignored. Set extend: { dedupe: false } to disable this.
Example:
// config.ts
export default {
colors: {
primary: "user_primary",
},
extends: ["./theme"],
};
// config.dev.ts
export default {
dev: true,
};
// theme/config.ts
export default {
extends: "../base",
colors: {
primary: "theme_primary",
secondary: "theme_secondary",
},
};
// base/config.ts
export default {
colors: {
primary: "base_primary",
text: "base_text",
},
};
The loaded configuration would look like this:
const config = {
dev: true,
colors: {
primary: "user_primary",
secondary: "theme_secondary",
text: "base_text",
},
};
Layers:
[
{
config: {/* theme config */},
configFile: "/path/to/theme/config.ts",
cwd: "/path/to/theme ",
},
{
config: {/* base config */},
configFile: "/path/to/base/config.ts",
cwd: "/path/to/base",
},
{
config: {/* dev config */},
configFile: "/path/to/config.dev.ts",
cwd: "/path/",
},
];
[!NOTE] Extending from remote sources requires the
gigetpeer dependency to be installed.# ✨ Auto-detect npx nypm install giget
You can also extend configuration from remote sources such as npm or github.
In the repo, there should be a config.ts (or config.{name}.ts) file to be considered as a valid config layer.
Example: Extend from a github repository
// config.ts
export default {
extends: "gh:user/repo",
};
Example: Extend from a github repository with branch and subpath
// config.ts
export default {
extends: "gh:user/repo/theme#dev",
};
Example: Extend a private repository and install dependencies:
// config.ts
export default {
extends: ["gh:user/repo", { auth: process.env.GITHUB_TOKEN, install: true }],
};
You can pass more options to giget: {} in layer config or disable it by setting it to false.
Refer to unjs/giget for more information.
Users can define environment-specific configuration using these config keys:
$test: {...}$development: {...}$production: {...}$env: { [env]: {...} }c12 tries to match envName and override environment config if specified.
Note: Environment will be applied when extending each configuration layer and to overrides (including per-layer extends overrides). This way layers can provide environment-specific configuration. RC files, package.json, defaultConfig and defaults do not support environment-specific keys.
Example:
export default {
// Default configuration
logLevel: "info",
// Environment overrides
$test: { logLevel: "silent" },
$development: { logLevel: "warning" },
$production: { logLevel: "error" },
$env: {
staging: { logLevel: "debug" },
},
};
defineConfig helpersLibraries that expose a typed config file can use createDefineConfig to ship a defineConfig-style helper for .ts configs.
import { createDefineConfig, loadConfig } from "c12";
interface MyConfig {
apiUrl: string;
logLevel?: "info" | "debug" | "error";
}
interface MyMeta {
name?: string;
author?: string;
}
export const defineMyConfig = createDefineConfig<MyConfig, MyMeta>();
// my.config.ts
export default defineMyConfig({
apiUrl: "https://api.example.com",
logLevel: "info",
$meta: {
name: "my-app",
author: "acme",
},
$development: {
logLevel: "debug",
},
});
createDefineConfig is an identity function at runtime. Its value is TypeScript inference: the returned helper accepts your config keys plus c12 reserved keys ($meta, $development, $production, $test, $env).
Pass the same generics to loadConfig so resolved config and meta stay typed:
const { config, meta } = await loadConfig<MyConfig, MyMeta>({
name: "my",
});
config.apiUrl; // string
meta?.author; // string | undefined
$meta$meta is a reserved namespace for layer metadata, not user-facing options. Use it for values such as layer name, author, repository, or credentials that describe the config layer itself.
c12 reads $meta (merged with sourceOptions.meta when extending) into the resolved layer's meta field and removes it from config, so it does not mix with regular options.
const { config, meta, layers } = await loadConfig<MyConfig, MyMeta>({});
// Regular options live on `config`
console.log(config.apiUrl);
// Layer metadata lives on `meta` / `layers[].meta`
console.log(meta?.name);
you can use watchConfig instead of loadConfig to load config and watch for changes, add and removals in all expected configuration paths and auto reload with new config.
Watching uses native (non-recursive) fs.watch on the directories of expected config paths, no extra dependencies are needed.
onWatch: This function is always called when config is updated, added, or removed before attempting to reload the config.acceptHMR: By implementing this function, you can compare old and new functions and return true if a full reload is not needed.onUpdate: This function is always called after the new config is updated. If acceptHMR returns true, it will be skipped.import { watchConfig } from "c12";
const config = watchConfig({
cwd: ".",
// debounce: 200 // Default is 100. You can set it to false to disable debounced watcher
onWatch: (event) => {
console.log("[watcher]", event.type, event.path);
},
acceptHMR({ oldConfig, newConfig, getDiff }) {
const diff = getDiff();
if (diff.length === 0) {
console.log("No config changed detected!");
return true; // No changes!
}
},
onUpdate({ oldConfig, newConfig, getDiff }) {
const diff = getDiff();
console.log("Config updated:\n" + diff.map((i) => i.toJSON()).join("\n"));
},
});
console.log("watching config files:", config.watchingFiles);
console.log("initial config", config.config);
// Stop watcher when not needed anymore
// await config.unwatch();
[!NOTE] This feature is experimental
Update or create a new configuration files.
Add magicast peer dependency:
# ✨ Auto-detect
npx nypm install -D magicast
Import util from c12/update
const { configFile, created } = await updateConfig({
cwd: ".",
configFile: "foo.config",
onCreate: ({ configFile }) => {
// You can prompt user if wants to create a new config file and return false to cancel
console.log(`Creating new config file in ${configFile}...`);
return "export default { test: true }";
},
onUpdate: (config) => {
// You can update the config contents just like an object
config.test2 = false;
},
});
console.log(`Config file ${created ? "created" : "updated"} in ${configFile}`);
You can use a function to define your configuration dynamically based on context.
// config.ts
export default (ctx) => {
return {
apiUrl: ctx?.dev ? "http://localhost:3000" : "https://api.example.com",
};
};
// Usage
import { loadConfig } from "c12";
const config = await loadConfig({
context: { dev: true },
});
c12 install size is now down to 380kB from 3.44MB (20 deps to 7 deps).
Loading TypeScript files is significantly faster (on cold cache) — simple TS config loads ~2.5x faster (bench).
watchConfig now uses native node:fs watching. The chokidar peer dependency and chokidarOptions option are removed (#260).Published under the MIT license.
Made by @pi0 and community 💛
🤖 auto updated with automd
© 2010 - cnpmjs.org x YWFE | Home | YWFE