In NestJS, what is a dynamic module returned by forRoot() or register(), and what does ConfigurableModuleBuilder generate for you?
answer
- a module built at call time
- module is the one required key
- extends the @Module metadata
- register, forRoot, forFeature
- an options token plus an Async twin
basics
~20 sA NestJS dynamic module is a DynamicModule object, @Module metadata plus a required module key, that a static method builds from the caller's options. ConfigurableModuleBuilder generates that method, its Async variant and the options token.
solid answer
~40 s`register()` and `forRoot()` are ordinary static methods returning a `DynamicModule`: the same `providers`, `imports`, `exports` and `controllers` keys as `@Module()`, plus a required `module` naming the class and an optional `global`. That object extends the decorator's static metadata. The usual pattern registers the caller's options as a `useValue` provider under a token that the module's services inject. By convention `register()` configures for the calling module, `forRoot()` once for the app, and `forFeature()` adjusts a `forRoot()` setup; each has an `Async` twin that builds options through DI. `new ConfigurableModuleBuilder<Options>().build()` writes this for you: a `ConfigurableModuleClass` with `register()` and `registerAsync()`, a generated `MODULE_OPTIONS_TOKEN`, plus `setClassMethodName()` and `setExtras()`.
code
typescript · 45 linesimport { ConfigurableModuleBuilder, Inject, Injectable, Module } from '@nestjs/common';
export interface PaymentsOptions {
apiKey: string;
currency: string;
}
export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
new ConfigurableModuleBuilder<PaymentsOptions>()
.setClassMethodName('forRoot')
.setExtras({ isGlobal: false }, (definition, extras) => ({
...definition,
global: extras.isGlobal,
}))
.build();
@Injectable()
export class PaymentsService {
constructor(@Inject(MODULE_OPTIONS_TOKEN) private readonly options: PaymentsOptions) {}
}
@Module({ providers: [PaymentsService], exports: [PaymentsService] })
export class PaymentsModule extends ConfigurableModuleClass {}
@Injectable()
export class SecretsService {
paymentKey(): string {
return process.env.PAYMENTS_API_KEY ?? '';
}
}
@Module({ providers: [SecretsService], exports: [SecretsService] })
export class SecretsModule {}
@Module({
imports: [
PaymentsModule.forRootAsync({
imports: [SecretsModule],
useFactory: (secrets: SecretsService) => ({ apiKey: secrets.paymentKey(), currency: 'EUR' }),
inject: [SecretsService],
isGlobal: true,
}),
],
})
export class AppModule {}go deeper
Recognise that forRoot() and register() return a module object built from options, and that the options usually become a provider the module's services inject.
Explain the DynamicModule keys, how they extend @Module() metadata, the register, forRoot and forFeature conventions, and the async options shape with imports and inject.
Use ConfigurableModuleBuilder rather than hand-writing async variants, and catch duplicated forRoot() calls and missing imports in async options before they become split state.
Decide which shared infrastructure ships as configurable modules, and keep global registration rare so feature modules still declare what they depend on.
## Static binding and its limit With **static binding**, a consumer writes `imports: [PaymentsModule]` and gets whatever `PaymentsModule` declared in its `@Module()` decorator. The consumer cannot influence how the host module's providers are configured. A **dynamic module** lets the importer pass options at import time: `imports: [PaymentsModule.forRoot({ currency: 'EUR' })]`. ## The DynamicModule object The static method is plain TypeScript. It can have any name and any arguments, and it returns an object implementing `DynamicModule`: - `module`: the module class itself, the **only required** key. - `providers`, `imports`, `exports`, `controllers`: the same keys as `@Module()` metadata. - `global`: when `true`, the module is registered in the global scope, like `@Global()`. What the method returns **extends** rather than replaces the metadata in the class's `@Module()` decorator, so a service declared statically and an options provider added dynamically live in the same module and can inject each other. The method may return the object synchronously or as a promise. The core trick is to bind the options into the container: the method adds `{ provide: PAYMENTS_OPTIONS, useValue: options }` to `providers`, and the module's service injects it with `@Inject(PAYMENTS_OPTIONS)`. The token stays private unless the module exports it. ## Naming conventions Nest's own packages follow guidelines, not hard rules: | Method | Meaning | |---|---| | `register()` | configure the module for the calling module only; each caller may pass different options | | `forRoot()` | configure once and reuse that configuration across the app | | `forFeature()` | reuse the `forRoot()` setup but adjust part of it for the calling module | Each usually has an asynchronous counterpart, `registerAsync()`, `forRootAsync()` or `forFeatureAsync()`, which resolves the options through dependency injection instead of taking them literally. ## The async options object The async variants accept the same shape: - `imports`: modules whose exported providers the factory, class or existing provider needs. - `useFactory` with `inject`: a function, sync or async, whose arguments are the `inject` tokens in order. - `useClass`: a class Nest instantiates whose method returns the options (`create()` by default). - `useExisting`: like `useClass`, but reuses a provider that already exists. - `provideInjectionTokensFrom`: a list of providers from which Nest picks the ones named in `inject`. Exactly one of `useFactory`, `useClass` and `useExisting` is chosen; they are mutually exclusive. Forgetting `imports` is the classic mistake: the factory's `inject` tokens must be resolvable inside the dynamic module. ## ConfigurableModuleBuilder Writing both the sync and async methods by hand is repetitive, so `@nestjs/common` provides `ConfigurableModuleBuilder`: 1. In a module-definition file, call `new ConfigurableModuleBuilder<PaymentsOptions>().build()`. It returns `ConfigurableModuleClass`, `MODULE_OPTIONS_TOKEN`, and the `OPTIONS_TYPE` and `ASYNC_OPTIONS_TYPE` helper types. 2. Make the module `extend ConfigurableModuleClass`. It gains static `register()` and `registerAsync()` by default. 3. Inject the options in services with `@Inject(MODULE_OPTIONS_TOKEN)`; the builder generated that token, so you define none. 4. Optionally call `setClassMethodName('forRoot')` to generate `forRoot()` and `forRootAsync()` instead, `setFactoryMethodName()` to rename the `create()` method an options class must implement, and `setExtras()` for flags such as `isGlobal` that change the module definition but stay out of the injected options object. To customise a generated method, override it and spread `super.register(options)` into your own return value. ## When a dynamic module is the right tool A dynamic module pays off when the same module must behave differently per consumer or per environment: an ID generator with a per-module prefix, a client whose base URL comes from secrets at startup, a feature-flag module fed by the root module. If every importer would pass the same literal options, a static module with a factory provider is simpler. If the options depend on other providers, write the async variant, because the plain method runs while the module graph is being declared, before any provider exists. ## Traps worth knowing - **Calling `forRoot()` twice.** Under the default `moduleIdGeneratorAlgorithm` (`'reference'`), each call yields a separately configured module with its own provider instances. To share one, call `forRoot()` once in a core module and list `PaymentsModule` in that module's `exports` without calling `forRoot()` again. - **Extras are not options.** A value consumed by `setExtras()` is absent from the object injected under `MODULE_OPTIONS_TOKEN`. - **Global everything.** `global: true` or an `isGlobal` extra spares imports, but the documentation warns that making everything global is not a good design decision.
- Two feature modules each call PaymentsModule.forRoot() with identical options. Do they share one PaymentsService?Not by default. With the default `moduleIdGeneratorAlgorithm` of `'reference'`, each call produces a separately configured module and its own provider instances. To share, call `forRoot()` once in a core module and re-export `PaymentsModule` from it. The `'deep-hash'` setting makes identical definitions resolve to one module, but that is an opt-in.
- Why does a forRootAsync() factory fail to resolve a service it lists in inject?The factory runs inside the dynamic module, so its `inject` tokens must be visible there. Add the module that exports them to the async options' `imports` array (or provide them via `provideInjectionTokensFrom`). The importing module's own imports do not help.
- A DynamicModule must repeat every key from the @Module() decorator.
- forRoot() and register() are reserved names that Nest calls automatically.
- Calling forRoot() in two modules always shares one configured instance.
- ConfigurableModuleBuilder generates forRoot() and forRootAsync() by default.
- An isGlobal extra appears inside the injected options object.