Getting started
@inversifyjs/config provides a ConfigContainerModule to load, optionally validate, and inject application configuration through the InversifyJS container.
Install dependencies
Install @inversifyjs/config, inversify, and a Standard Schema library. The example below uses Zod:
- npm
- yarn
- pnpm
npm install inversify @inversifyjs/config zod
yarn add inversify @inversifyjs/config zod
pnpm install inversify @inversifyjs/config zod
Validation is optional. If you skip it, you only need inversify and @inversifyjs/config.
Optional source helpers live in separate packages:
@inversifyjs/config-dotenvfor.envfiles@inversifyjs/config-yamlfor YAML files
Load your first config module
Provide a config source, optionally validate it with a Standard Schema (Zod in this example), and load the module with container.loadAsync:
import {
ConfigContainerModule,
type ConfigService,
configServiceIdentifier,
object,
} from '@inversifyjs/config';
import { Container } from 'inversify';
import { z } from 'zod';
const appConfigSchema = z.object({
DATABASE_URL: z.url(),
PORT: z.coerce.number().default(3000),
});
type AppConfig = z.infer<typeof appConfigSchema>;
export async function bootstrap(): Promise<AppConfig> {
const container: Container = new Container();
await container.loadAsync(
ConfigContainerModule.fromOptions({
source: object({
DATABASE_URL: 'postgres://localhost:5432/app',
PORT: '3000',
}),
validate: appConfigSchema,
}),
);
return container.get<ConfigService<AppConfig>>(configServiceIdentifier).get();
}
tip
Config loading and validation happen while the module loads, so invalid configuration fails at bootstrap instead of on first resolve.