Kest

Search

Search the documentation

Fundamentals

Dynamic modules

Modules configured when the application starts: forRoot, register, forRootAsync, and your own.

A normal module is fixed: its providers are known when you write it. A dynamic module is configured when the application starts, with values only the application knows: a database URL, a secret key, a feature switch. By convention it has a forRoot function (configure it once for the whole application) or register (configure it, possibly several times).

Kest.run<AppModule> {
    import(
        ConfigModule.forRoot { envFiles = listOf(".env") },
        JwtModule.register { secret = System.getenv("JWT_SECRET"); expiresIn = Duration.ofHours(1) },
        ThrottlerModule.forRoot { limit = 100 },
        CacheModule.register { ttl = Duration.ofSeconds(30) },
    )
}

The block is a Kotlin lambda over an options object, so you get auto-completion and type checking for every setting, and nothing is read from magic strings.

Configuring from other providers: forRootAsync

Often a setting comes from another provider (the configuration service). The forRootAsync form hands you the container (or a typed provider):

import(
    ConfigModule.forRoot(),
    SentryModule.forRootAsync { r -> dsn = r.get(ConfigService::class).getOrThrow("sentry.dsn") },
)
// typed shortcut for one dependency:
OpenTelemetryModule.forRootAsync { config: ConfigService -> serviceName = config.getOrThrow("app.name") }

The module is built after the providers it reads, in the right order.

Writing your own

Say you want import(PostgresModule.forRoot()) to set up the ORM from your configuration and export it. In NestJS this is a module with a static forRoot that returns { module, imports, providers, exports }. In Kest, DynamicModule.create is the same idea:

@Provided data class PostgresModuleOptions(val isGlobal: Boolean = true)
 
@Module
class PostgresModule {
    companion object {
        fun forRoot(options: PostgresModuleOptions = PostgresModuleOptions()) = DynamicModule.create(PostgresModule::class) {
            global = options.isGlobal
            imports(
                ConfigModule.forRoot(),                                                  // other dynamic modules this one needs
                OrmModule.forRootAsync { config: ConfigService -> buildPostgresOptions(config) },
            )
            provide(options)                                                              // a value
            provide<Pool> { r -> Pool(r.get(ConfigService::class).getOrThrow<String>("pg.url")) }   // a factory, with the container
            exports(OrmModule::class)
        }
    }
}
 
Kest.run<AppModule> { import(PostgresModule.forRoot()) }
  • imports(...) takes other dynamic modules. They are registered with yours, and a module imported by several of them is registered once.
  • provide(value), provide<T> { r -> ... } and provide(Token) { r -> ... } are useValue and useFactory (Custom providers).
  • global and exports are recorded but do not hide anything: every provider is already visible to every module, because the module graph is checked at compile time rather than enforced at run time. Types supplied this way are marked @Provided so the compiler knows they exist.
  • Java: DynamicModule.create(PostgresModule.class, b -> { b.imports(...); b.provide(...); }).

Design tips for a good forRoot

  • Put every setting in an options class with sensible defaults, so the common case is forRoot().
  • Offer forRootAsync when settings often come from configuration.
  • Validate options early and throw a clear KestException ("DSN is not a valid URL") so a mistake fails at start-up, not at the first request.
  • Keep the module's providers small; let users depend on your exported service or interface, not your internals.

Static or dynamic?

Use a normal @ModuleUse a dynamic module
your own feature code (users, orders)a library or infrastructure (database, JWT, cache)
nothing to configureneeds settings from the environment

Read more