Skip to main content

Sources

ConfigContainerModule accepts a single ConfigSource. Built-in helpers cover the common cases; for multiple inputs, compose them in a custom source.

object

Returns a static configuration object. Useful for defaults and tests.

import { type ConfigSource, object } from '@inversifyjs/config';

export const source: ConfigSource = object({
HOST: 'localhost',
PORT: 3000,
});

factory

Delegates loading to a function. The function may be sync or async.

import { type ConfigSource, factory } from '@inversifyjs/config';

export const source: ConfigSource = factory(() => ({
PORT: Number(process.env['PORT'] ?? '3000'),
}));

processEnv

Reads values from process.env.

interface ProcessEnvOptions {
pick?: string[];
}

When pick is omitted, all environment variables are included.

import { type ConfigSource, processEnv } from '@inversifyjs/config';

export const source: ConfigSource = processEnv({
pick: ['DATABASE_URL', 'PORT'],
});

jsonFile

Reads and parses a JSON object file. The file must contain a JSON object (not an array or primitive).

interface JsonFileOptions {
path: string;
}
import { type ConfigSource, jsonFile } from '@inversifyjs/config';

export const source: ConfigSource = jsonFile({
path: './config.json',
});

Custom sources

Need multiple files or precedence rules? Implement ConfigSource yourself:

import {
type ConfigObject,
type ConfigSource,
object,
processEnv,
} from '@inversifyjs/config';

export function mergedSource(): ConfigSource {
const defaults: ConfigSource = object({
PORT: '3000',
});
const env: ConfigSource = processEnv({
pick: ['PORT', 'DATABASE_URL'],
});

return {
async load(): Promise<ConfigObject> {
return {
...(await Promise.resolve(defaults.load())),
...(await Promise.resolve(env.load())),
};
},
};
}

Optional packages provide additional helpers:

  • dotenv via @inversifyjs/config-dotenv
  • YAML via @inversifyjs/config-yaml