Application
Configuration
Environment variables, .env, .properties, YAML and JSON files, validation and typed getters.
config is @nestjs/config: it merges several sources into one flat map and gives you typed access.
Kest.run<AppModule> {
import(ConfigModule.forRoot {
envFiles = listOf(".env.local", ".env") // the first file listed wins, as in NestJS envFilePath
yaml("config/app.yaml")
json("config/features.json")
properties("application.properties")
file("config/${System.getenv("APP_ENV") ?: "dev"}.yml") // by extension: .yaml/.yml, .json, .properties, anything else is a .env file
load({ mapOf("app" to mapOf("name" to "Shop")) }) // from code
required = listOf("DATABASE_URL")
validate { values -> check(values["PORT"]?.toIntOrNull() in 1..65535) { "PORT must be a port number" } }
})
}Priority
Highest first: the process environment, .env files, then files and loaders in the order you listed them, later ones overriding earlier ones. Among .env files the first one listed wins (NestJS envFilePath). Set override = true to put .env values above the process environment (NestJS override). A missing file is skipped. ${OTHER} and ${OTHER:-default} inside values are expanded.
YAML and JSON
Nested objects become dotted keys, so this file:
app:
name: Shop
port: 8081
tags: [a, b, c]
limits:
- name: free
max: 10
- name: pro
max: 100
db:
url: "jdbc:postgresql://localhost/shop"reads as app.name, app.port, app.tags (the list joined with commas, for getList), app.tags.0, app.limits.1.name, app.limits.1.max, db.url. null values are absent. A file that is not a JSON or YAML object, or does not parse, stops startup with a ConfigException naming the file.
Injecting a value with @Value
Instead of injecting ConfigService and reading keys, put the value on a constructor parameter. Kest reads it, converts it to the parameter's type, and passes it in:
@Injectable
class Mailer(
@Value("mail.host") val host: String,
@Value("mail.port", default = "587") val port: Int,
@Value("mail.timeout", default = "30s") val timeout: Duration,
@Value("mail.cc") val cc: List<String>?, // null when not set
)- A key with no default and a non-null type that is missing stops start-up with
Missing required configuration 'mail.host' (needed by @Value). - A nullable parameter (
String?, or a@Nullable/java.util.Optionalone) isnullwhen missing. defaultis a string, converted the same way as the value ("587"becomes587,"30s"aDuration,"a,b"aList).- The usual conversions apply:
String, numbers,Boolean,Duration, enums,List<T>,URI,UUID, dates. A value that does not convert fails start-up and names the key. - Environment names still win:
mail.hostis overridden byMAIL_HOST. - It works in Kotlin and Java (the processor generates the lookup, so a wrong type is not possible), and in Scala and Groovy (read at start-up).
ConfigModulemust be imported, as for any use of the config.
For a whole section as an object, use registerAs with @Inject("config:name") or config.bind<T>("section") below.
Reading values
@Injectable
class Settings(private val config: ConfigService) {
val port = config.getInt("app.port", 8080)
val tags = config.getList("app.tags")
val db = config.namespace("db") // db.getRequired("url")
}get, getString, getInt, getLong, getDouble, getBoolean, getList, getRequired (throws if missing), namespace, asMap. An environment-style name wins over a dotted one: app.port is overridden by APP_PORT.
Configuring other modules from it
The NestJS pattern, TypeOrmModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: buildPostgresOptions }), is forRootAsync (or registerAsync) with a lambda that receives the injected provider:
Kest.run<AppModule> {
import(
ConfigModule.forRoot { yaml("config/app.yaml"); register(database) },
OrmModule.forRootAsync { config: ConfigService -> // inject: [ConfigService]
synchronize = config.getAs("db.sync", false)
postgres("main", config.getOrThrow("db.main.url"), config.getOrThrow("db.main.user"), config.getOrThrow("db.main.password"))
mongo("events", config.getOrThrow("db.events.uri"), database = "events")
},
JwtModule.registerAsync { config: ConfigService -> secret = config.getOrThrow("jwt.secret"); expiresIn = Duration.ofHours(config.getAs("jwt.hours", 1).toLong()) },
ThrottlerModule.forRootAsync { r -> limit = r.get(ConfigService::class).getAs("throttle.limit", 100) }, // or take the container and ask for anything
)
}The module is built the first time something needs it, from the container, so the ConfigService is already there whatever the order of import(...). Both forms exist: a typed one-provider lambda ({ config: ConfigService -> ... }), and { r -> ... } that gets the container (r.get(...)) for several providers. A missing key stops startup with its name.
| Module | Async form |
|---|---|
OrmModule | forRootAsync (provides Orm and TransactionManagers) |
JwtModule | registerAsync |
ThrottlerModule, QueueModule, MailerModule, MetricsModule, OpenTelemetryModule | forRootAsync |
CacheModule | registerAsync |
DynamicModule.async(module, provides) { r -> ... } builds the same for your own modules.
Typed values and namespaces
config.getOrThrow("db.url") // String, or ConfigException naming the key (also getRequired)
config.get<Int>("db.port") // NestJS configService.get<number>("db.port"): converted to the type, null when missing
config.get<Int>("db.port", 5432) // with a default
config.getOrThrow<String>("db.url") // NestJS getOrThrow<string>(...): converted and required
config.get<Duration>("http.timeout") // 30s, 500ms, 5m, 2h, 1d, PT30S or plain seconds
config.get<List<Int>>("ports") // "80, 443" -> [80, 443]; Set<T> too
config.get<LogMode>("log.mode") // enums, case-insensitively; also BigDecimal, URI, Path, File, UUID, Instant, LocalDate, Short, Float...
config.getAs<Int>("db.port") // the same as get<Int>, kept for older code
config.getAs("pool.size", 10) // with a default
config.getOrThrowAs<Int>("db.port") // converted, and requiredA value that does not convert ("abc" as an Int) is a ConfigException that names the key and the value.
Namespaced configuration objects, NestJS registerAs:
data class DbSettings(val url: String, val pool: Int)
val database = registerAs("database") { c -> DbSettings(c.getOrThrow("db.url"), c.getAs("db.pool", 10)) }
ConfigModule.forRoot { yaml("app.yaml"); register(database) }
@Injectable class Repo(@Inject("config:database") private val db: DbSettings) // by token
OrmModule.forRootAsync { r -> val db = r.get(database.token); postgres("main", db.url, ...) }Loading without a container
ConfigModule.load(ConfigOptions().apply { ... }) returns the merged map, for use in main before the application exists.
Binding a whole section
bind turns a section into a class, with snake_case, kebab-case and camelCase treated alike and unknown keys ignored:
data class DbSettings(val host: String, val port: Int, val maxPoolSize: Int = 10, val ssl: Boolean = false)
val db = config.bind<DbSettings>("db") // db.host, db.port, db.max_pool_size, db.sslA value that does not convert fails with a ConfigException that names the section and the problem.
Feature configuration, and switching modules on and off
// NestJS ConfigModule.forFeature(registerAs(...)): a feature module brings its own namespace
val search = registerAs("search") { c -> SearchSettings(c.getOrThrow("search.url"), c.get("search.timeout", Duration.ofSeconds(5))) }
DynamicModule.create(SearchModule::class) { imports(ConfigModule.forFeature(search)) } // inject with @Inject("config:search")
// NestJS ConditionalModule.registerWhen: only register the module when the flag is on
import(ConditionalModule.registerWhen(MetricsModule.forRoot(), "FEATURE_METRICS"))
import(ConditionalModule.registerWhen(AdminModule.forRoot()) { c -> c.get<String>("APP_ENV") != "prod" })Unlike NestJS forFeature, there is no initialisation-order caveat: the namespace is built when it is first needed, from the loaded ConfigService.