Dynamic modules let you create modules that can change what they provide based on input. This helps you reuse code and configure features easily.
0
0
Dynamic modules in NestJS
Introduction
When you want to create a module that can be configured differently in different parts of your app.
When you need to provide services or providers based on user settings or environment variables.
When building reusable libraries that need flexible setup options.
When you want to avoid repeating similar module code with small differences.
When you want to load modules conditionally depending on app needs.
Syntax
NestJS
import { Module, DynamicModule } from '@nestjs/common'; @Module({}) export class MyDynamicModule { static forRoot(options: MyOptions): DynamicModule { return { module: MyDynamicModule, providers: [ { provide: 'CONFIG_OPTIONS', useValue: options }, MyService, ], exports: [MyService], }; } }
The static method (often named forRoot) returns a DynamicModule object.
This object defines what the module provides, including providers and exports.
Examples
Example of a dynamic module that accepts an API key and provides a service using it.
NestJS
static forRoot(options: { apiKey: string }): DynamicModule {
return {
module: MyDynamicModule,
providers: [
{ provide: 'API_KEY', useValue: options.apiKey },
ApiService,
],
exports: [ApiService],
};
}Another static method to configure the module for a specific feature.
NestJS
static forFeature(featureName: string): DynamicModule {
return {
module: MyDynamicModule,
providers: [
{ provide: 'FEATURE_NAME', useValue: featureName },
FeatureService,
],
exports: [FeatureService],
};
}Sample Program
This dynamic module lets you set a custom greeting message. The service uses that message to greet a user by name.
NestJS
import { Module, Injectable, Inject } from '@nestjs/common'; @Injectable() class GreetingService { constructor(@Inject('GREETING') private greeting: string) {} sayHello(name: string): string { return `${this.greeting}, ${name}!`; } } @Module({}) export class GreetingModule { static forRoot(greeting: string): DynamicModule { return { module: GreetingModule, providers: [ { provide: 'GREETING', useValue: greeting }, GreetingService, ], exports: [GreetingService], }; } } // Usage example (not part of module): // const appModule = { // imports: [GreetingModule.forRoot('Hello')], // }; // Then inject GreetingService and call sayHello('Alice') to get 'Hello, Alice!'
OutputSuccess
Important Notes
Dynamic modules help keep your app flexible and DRY (Don't Repeat Yourself).
Always export the providers you want other modules to use.
Use descriptive names for your static methods like forRoot or forFeature to clarify their purpose.
Summary
Dynamic modules let you configure modules with custom options.
They return a DynamicModule object with providers and exports.
This pattern helps reuse and customize modules easily.