Configuration
MiiaJS provides a ConfigModule for loading and validating environment variables with any ZodLike schema.
Setup
import { Module } from '@miiajs/core'
import { ConfigModule } from '@miiajs/config'
import { z } from 'zod'
const EnvSchema = z.object({
PORT: z.string().default('3000'),
DATABASE_URL: z.string(),
JWT_SECRET: z.string(),
DEBUG: z.string().default('false'),
})
@Module({
imports: [
ConfigModule.configure({ schema: EnvSchema }, { global: true }),
],
})
class AppModule {}
ConfigModule.configure() validates process.env against your schema at startup. If validation fails, the application throws with detailed error messages.
ConfigModule.configure() exports ConfigService. { global: true } makes it visible to every module, the usual choice for configuration; without it, a module that injects ConfigService imports ConfigModule bare (imports: [ConfigModule]) and gets this configuration.
Using ConfigService
Inject ConfigService to access validated values:
import { Injectable, inject } from '@miiajs/core'
import { ConfigService } from '@miiajs/config'
@Injectable()
class DatabaseService {
private configService = inject(ConfigService)
connect() {
const url = this.configService.getOrThrow('DATABASE_URL')
const port = this.configService.get('PORT') ?? '3000'
// ...
}
}
API
| Method | Returns | On missing key |
|---|---|---|
get(key) | T[K] | Returns undefined |
getOrThrow(key) | Exclude<T[K], undefined> | Throws Error |
Values are a snapshot
ConfigModule reads its values once, at startup, with or without a schema. A later change to process.env, or to the env object you passed, is not seen by ConfigService.
- Without a schema the values are a frozen copy of
env. Only the top level is frozen - the values are strings. - With a schema the values are a deeply frozen copy of what the schema returns: its plain objects and arrays are copied and frozen, so writing to them throws
TypeError.Map,Set,Dateand class instances atransformreturns are kept as they are, not frozen.
const EnvSchema = z.object({
CORS_ORIGIN: z.string().transform((v) => v.split(',')),
})
config.get('CORS_ORIGIN').push('https://admin.example.com') // TypeError: the array is frozen
const origins = [...config.get('CORS_ORIGIN'), 'https://admin.example.com'] // a copy you own
What this means in practice:
- In tests, change
process.envbeforeinit()(orTestApp.compile()), passenv, or overrideConfigModule. - Copy an object value before you hand it to an API that mutates its input.
- On Deno, a config without a schema reads the whole environment at startup, so it needs
--allow-envwithout a list of names. With a schema only the keys the schema reads are read - forz.object(), its own keys.
Factory configuration
Use a factory function to resolve config from DI:
import { DrizzleModule } from '@miiajs/drizzle'
@Module({
imports: [
ConfigModule.configure({ schema: EnvSchema }, { global: true }),
DrizzleModule.configure((resolve) => {
const config = resolve(ConfigService)
return {
dialect: 'postgres',
connection: { url: config.getOrThrow('DATABASE_URL') },
}
}),
],
})
class AppModule {}
The resolve function reaches what the configured module sees plus what the module importing the configure() result sees - here AppModule, so the factory can read ConfigService from it (see Configured modules).
Custom env source
By default, ConfigModule reads from process.env. You can pass a custom source:
ConfigModule.configure({
schema: EnvSchema,
env: {
PORT: '8080',
DATABASE_URL: 'postgres://localhost:5432/test',
JWT_SECRET: 'test-secret',
},
})
This is useful for testing or when loading from a custom source. Feature configs read the same env.
Feature configuration
The root schema describes the variables of the whole app. A feature module can own its variables instead: defineConfig() gives them a name and a schema and returns a typed token, and ConfigModule.register() provides that token in the module.
// payments/payments.config.ts
import { defineConfig } from '@miiajs/config'
import { z } from 'zod'
export const paymentsConfig = defineConfig(
'payments',
z.object({
STRIPE_KEY: z.string(),
CURRENCY: z.string().default('usd'),
METHODS: z.string().default('card').transform((v) => v.split(',')),
}),
)
// payments/payments.module.ts
import { Module } from '@miiajs/core'
import { ConfigModule } from '@miiajs/config'
@Module({
imports: [ConfigModule.register(paymentsConfig)],
providers: [PaymentsService],
})
export class PaymentsModule {}
// payments/payments.service.ts
import { Injectable, inject } from '@miiajs/core'
@Injectable()
export class PaymentsService {
// Readonly<{ STRIPE_KEY: string; CURRENCY: string; METHODS: string[] }>
private config = inject(paymentsConfig)
charge() {
const key = this.config.STRIPE_KEY
// ...
}
}
- Typed and frozen.
inject(paymentsConfig)is typed from what the schema returns, defaults and transforms included. The value is validated once, at startup, and frozen the same way as the root values (see Values are a snapshot): writing to it, or to an object or array inside it, throwsTypeError. - Validation errors name the config. A failure stops startup:
[Miia] Config validation failed for 'payments': - STRIPE_KEY: Invalid input: expected string, received undefined - Env source. The schema reads the same env as the root
ConfigModule.configure()- itsenvoption, orprocess.env. In an app withoutConfigModule.configure()it readsprocess.env. - One instance. Several modules may register the same config. They share one instance, validated once. The token is the one
defineConfig()returned - export it from one file and import it everywhere; a seconddefineConfig('payments', ...)call is a different token. - Visibility.
register()reads the env through the module that imports it, so that module must see the root config: make the root config global (ConfigModule.configure(options, { global: true }), the usual choice) or addConfigModuleto the module'simports. Otherwise startup fails with a module boundary violation that names both fixes:Config(payments) (ConfigModule.register(payments) in PaymentsModule) injects ConfigSource (ConfigModule in AppModule), which is not global: - make it global: ConfigModule.configure(options, { global: true }) - or add ConfigModule to PaymentsModule `imports` - Tests. The token is overridden like any provider - the schema then does not run:
TestApp.create(AppModule).override(paymentsConfig, { STRIPE_KEY: 'sk_test' })(see Testing).
How this differs from the root config: ConfigService<Env> reads the app-wide schema key by key, with Env passed as a type argument where you inject it. A feature config keeps its variables next to the module that uses them - the root schema does not list them - and comes as one typed object from inject().
Schema requirements
The schema must implement a safeParse() method (ZodLike interface):
interface ZodLike<T = any> {
safeParse(data: unknown):
| { success: true; data: T }
| { success: false; error: { issues: { message: string; path?: (string | number)[] }[] } }
}
@miiajs/config does not declare zod as a peer dependency - bring your own validator. Any library or custom object that exposes a safeParse method matching the shape above works.
Using non-Zod validators
Zod implements ZodLike natively, but you can plug in any modern validator. The two most common alternatives:
Valibot
Valibot's safeParse returns { success, output, issues } - one tiny adapter:
import * as v from 'valibot'
import { ConfigModule } from '@miiajs/config'
const schema = v.object({
PORT: v.pipe(v.string(), v.transform(Number), v.number()),
DATABASE_URL: v.string(),
})
ConfigModule.configure({
schema: {
safeParse: (data) => {
const r = v.safeParse(schema, data)
return r.success
? { success: true, data: r.output }
: { success: false, error: { issues: r.issues.map((i) => ({ message: i.message, path: i.path?.map((p) => p.key) })) } }
},
},
})
ArkType
ArkType's type(...) already returns either the parsed value or an error array - similar shape, similar adapter:
import { type } from 'arktype'
import { ConfigModule } from '@miiajs/config'
const schema = type({
PORT: 'string.numeric.parse',
DATABASE_URL: 'string',
})
ConfigModule.configure({
schema: {
safeParse: (data) => {
const r = schema(data)
return r instanceof type.errors
? { success: false, error: { issues: r.map((e) => ({ message: e.message, path: e.path })) } }
: { success: true, data: r }
},
},
})
Hand-rolled
For simple cases you don't need a library at all:
ConfigModule.configure({
schema: {
safeParse: (data: any) => {
if (!data.DATABASE_URL) {
return { success: false, error: { issues: [{ message: 'DATABASE_URL is required', path: ['DATABASE_URL'] }] } }
}
return { success: true, data: { ...data, PORT: Number(data.PORT ?? 3000) } }
},
},
})