Tutorial · Step 7 of 12
Configuration
Typed, validated settings that stop a misconfigured app from booting at all.
Settings as a module#
Configuration is just another module. configModule.forRoot(...factories) runs each factory, deep-merges the results, and resolves to a module that puts a typed configService on the startup context. It is async — loaders run once, when you await it — so the app is only built from valid settings. include it first so everything after it can read the settings:
// src/config/app.config.ts
import { defineConfig } from "@rhythmjs/config";
import { z } from "zod";
export const appConfig = defineConfig(
z.object({ port: z.coerce.number().default(3000) }),
() => ({ port: process.env.PORT }),
);// src/config/settings.module.ts
import { configModule } from "@rhythmjs/config";
import { configs } from ".";
export const settingsModule = await configModule.forRoot(...configs); // validated once, at import// src/app.module.ts
import { include } from "@rhythmjs/rhythm";
import { settingsModule } from "./config/settings.module";
export const appModule = new Rhythm({ name: "app" })
.register(include(settingsModule, ({ configService }) => ({ configService })))
.register(decorate(() => ({ appService })))
.use(mount(appController))
.use(mount(notesModule));settingsModule is an infrastructure module in the sense of the modules step: one instance, created once and exported. Anything that includes it gets a typed configService on its startup context, and include is sequential, so the next register can already read it. A feature that needs settings includes settingsModule itself, like it includes any other infrastructure, and a router that declares AppConfigContext (from src/config/index.ts below) as its context type can then call ctx.configService.get("port"): the path and the value are typed, and the app that serves it is rejected by toFetchHandler when nothing supplies it. Bun loads .env files natively, and factories read process.env themselves; there is no dotenv layer.
Namespaces with registerAs#
registerAs(token, schema, factory) names a config namespace and validates it with any Standard Schema validator. Validation failures from all factories aggregate into one startup error, rejected from await configModule.forRoot(...) — the app refuses to boot on malformed config rather than failing later at 3 a.m.:
// src/config/database.config.ts
import { registerAs } from "@rhythmjs/config";
import { z } from "zod";
export const databaseConfig = registerAs(
"database",
z.object({
url: z.url("DATABASE_URL must be a valid URL"),
poolSize: z.coerce.number().int().min(1).default(10),
}),
() => ({
url: process.env.DATABASE_URL ?? "",
poolSize: process.env.DATABASE_POOL_SIZE,
}),
);Collect the factories in one place; settingsModule registers them all:
// src/config/index.ts
import type { ConfigContext } from "@rhythmjs/config";
import { appConfig } from "./app.config";
import { databaseConfig } from "./database.config";
export const configs = [appConfig, databaseConfig] as const;
export type AppConfigContext = ConfigContext<typeof configs>; // what configService offers// anywhere settingsModule was included:
ctx.configService.get("database.url"); // string (validated URL)
ctx.configService.get("database.poolSize"); // number, defaulted
ctx.configService.getOrThrow("port"); // throws if missingConfig at startup#
Code that runs outside the pipeline, like main.ts or an infrastructure module's top level, is ordinary top-level code, so it just reads settings first. Config factories are callable directly, and a failure throws before anything else is built:
// src/main.ts
const { port } = await appConfig();
// { port: 3000 } — validated or thrown
const server = Bun.serve({ port, fetch: toFetchHandler(appModule) });The next step uses the same call to open the database with the validated database.url, in the database module.
Some schema libraries embed the received value in issue messages. Keep secret-bearing fields' error messages custom (z.url("DATABASE_URL must be a valid URL")) so a failed boot never prints the secret into logs.