So far in this series, we’ve defined many different modules that can group provides and controllers. None of them was customizable, though. In this article, we learn how to create dynamic modules that are customizable, making them easier to reuse. While doing that, we rewrite some of our old code to use dynamic modules.
If you want to know more about modules in general, check out API with NestJS #6. Looking into dependency injection and modules
To better illustrate why we might want to use dynamic modules, let’s look at the EmailModule we’ve defined in the API with NestJS #25. Sending scheduled emails with cron and Nodemailer article.
1import { Module } from '@nestjs/common';
2import EmailService from './email.service';
3import { ConfigModule } from '@nestjs/config';
4
5@Module({
6 imports: [ConfigModule],
7 controllers: [],
8 providers: [EmailService],
9 exports: [EmailService],
10})
11export class EmailModule {}The above module contains the EmailService provider and exports it. Let’s look under the hood:
1import { Injectable } from '@nestjs/common';
2import { createTransport } from 'nodemailer';
3import * as Mail from 'nodemailer/lib/mailer';
4import { ConfigService } from '@nestjs/config';
5
6@Injectable()
7export default class EmailService {
8 private nodemailerTransport: Mail;
9
10 constructor(private readonly configService: ConfigService) {
11 this.nodemailerTransport = createTransport({
12 service: configService.get('EMAIL_SERVICE'),
13 auth: {
14 user: configService.get('EMAIL_USER'),
15 pass: configService.get('EMAIL_PASSWORD'),
16 },
17 });
18 }
19
20 sendMail(options: Mail.Options) {
21 return this.nodemailerTransport.sendMail(options);
22 }
23}The crucial thing to notice above is that our EmailService will always have the same configuration. So, for example, we can’t have a separate email for password confirmation and a separate email for the newsletter. To deal with this issue, we can create a dynamic module.
Creating a dynamic module
To create a dynamic module, let’s add a static method to the EmailModule.
1import { DynamicModule, Module } from '@nestjs/common';
2import EmailService from './email.service';
3import { EMAIL_CONFIG_OPTIONS } from './constants';
4import EmailOptions from './emailOptions.interface';
5
6@Module({})
7export class EmailModule {
8 static register(options: EmailOptions): DynamicModule {
9 return {
10 module: EmailModule,
11 providers: [
12 {
13 provide: EMAIL_CONFIG_OPTIONS,
14 useValue: options,
15 },
16 EmailService,
17 ],
18 exports: [EmailService],
19 };
20 }
21}Above, instead of putting our module definition inside the @Module({}) decorator, we return it from the register method. We allow the user to provide the EmailOptions as the argument to the register function.
1interface EmailOptions {
2 service: string;
3 user: string;
4 password: string;
5}
6
7export default EmailOptions;We also define a unique EMAIL_CONFIG_OPTIONS constant in a separate file.
1export const EMAIL_CONFIG_OPTIONS = 'EMAIL_CONFIG_OPTIONS';We can also use a Symbol.
In the register() method, we add the EMAIL_CONFIG_OPTIONS to the list of providers along with the option’s value. Thanks to the above, the configuration will be available in the EmailService through the @Inject() decorator.
1import { Inject, Injectable } from '@nestjs/common';
2import { createTransport } from 'nodemailer';
3import { EMAIL_CONFIG_OPTIONS } from './constants';
4import Mail from 'nodemailer/lib/mailer';
5import EmailOptions from './emailOptions.interface';
6
7@Injectable()
8export default class EmailService {
9 private nodemailerTransport: Mail;
10
11 constructor(@Inject(EMAIL_CONFIG_OPTIONS) private options: EmailOptions) {
12 this.nodemailerTransport = createTransport({
13 service: options.service,
14 auth: {
15 user: options.user,
16 pass: options.password,
17 },
18 });
19 }
20
21 sendMail(options: Mail.Options) {
22 return this.nodemailerTransport.sendMail(options);
23 }
24}Thanks to our approach, we can now configure the module when importing it.
1import { Module } from '@nestjs/common';
2import { EmailConfirmationService } from './emailConfirmation.service';
3import { ConfigModule } from '@nestjs/config';
4import { EmailModule } from '../email/email.module';
5import { JwtModule } from '@nestjs/jwt';
6import { EmailConfirmationController } from './emailConfirmation.controller';
7import { UsersModule } from '../users/users.module';
8
9@Module({
10 imports: [
11 ConfigModule,
12 EmailModule.register({
13 service: 'gmail',
14 user: 'email.account@gmail.com',
15 password: 'mystrongpassword',
16 }),
17 JwtModule.register({}),
18 UsersModule,
19 ],
20 providers: [EmailConfirmationService],
21 exports: [EmailConfirmationService],
22 controllers: [EmailConfirmationController],
23})
24export class EmailConfirmationModule {}Asynchronous configuration
There is a significant drawback to the above approach because we no longer can use the ConfigService when setting up our email provider. Fortunately, we can deal with this issue by creating an asynchronous version of our register method. It will have access to the dependency injection mechanism built into NestJS.
Our registerAsync method will also receive the options, but the type used for its argument is slightly different than register.
1EmailModule.registerAsync({
2 imports: [ConfigModule],
3 inject: [ConfigService],
4 useFactory: (configService: ConfigService) => ({
5 service: configService.get('EMAIL_SERVICE'),
6 user: configService.get('EMAIL_USER'),
7 password: configService.get('EMAIL_PASSWORD'),
8 }),
9}),Let’s go through all of the properties above:
- imports – a list of modules we want the EmailModule to import because we need them in useFactory,
- inject – a list of providers we want NestJS to inject into the context of the useFactory function,
- useFactory – a function that returns the value for our EMAIL_CONFIG_OPTIONS provider.
A straightforward way to create a type with the above properties is to use the ModuleMetadata and FactoryProvider interfaces.
1import { ModuleMetadata } from '@nestjs/common';
2import EmailOptions from './emailOptions.interface';
3import { FactoryProvider } from '@nestjs/common/interfaces/modules/provider.interface';
4
5type EmailAsyncOptions = Pick<ModuleMetadata, 'imports'> &
6 Pick<FactoryProvider<EmailOptions>, 'useFactory' | 'inject'>;
7
8export default EmailAsyncOptions;Please notice that FactoryProvider is generic and we pass EmailOptions to it to enforce the correct configuration.
Once we have the above, we can define our registerAsync method.
1import { DynamicModule, Module } from '@nestjs/common';
2import EmailService from './email.service';
3import { EMAIL_CONFIG_OPTIONS } from './constants';
4import EmailOptions from './emailOptions.interface';
5import EmailAsyncOptions from './emailAsyncOptions.type';
6
7@Module({})
8export class EmailModule {
9 static register(options: EmailOptions): DynamicModule {
10 return {
11 module: EmailModule,
12 providers: [
13 {
14 provide: EMAIL_CONFIG_OPTIONS,
15 useValue: options,
16 },
17 EmailService,
18 ],
19 exports: [EmailService],
20 };
21 }
22
23 static registerAsync(options: EmailAsyncOptions): DynamicModule {
24 return {
25 module: EmailModule,
26 imports: options.imports,
27 providers: [
28 {
29 provide: EMAIL_CONFIG_OPTIONS,
30 useFactory: options.useFactory,
31 inject: options.inject,
32 },
33 EmailService,
34 ],
35 exports: [EmailService],
36 };
37 }
38}Under the hood, our registerAsync method is very similar to register. The difference is that it uses useFactory and inject instead of useValue. It also accepts an array of additional modules to import through options.imports.
Thanks to creating a way to configure the EmailModule asynchronously, we can now use it with various configurations depending on the use case and still use the dependency injection mechanism.
1EmailModule.registerAsync({
2 imports: [ConfigModule],
3 inject: [ConfigService],
4 useFactory: (configService: ConfigService) => ({
5 service: configService.get('NEWSLETTER_EMAIL_SERVICE'),
6 user: configService.get('NEWSLETTER_EMAIL_USER'),
7 password: configService.get('NEWSLETTER_EMAIL_PASSWORD'),
8 }),
9}),Naming conventions
So far, we’ve only defined the register and registerAsync methods. It is significant to notice that NestJS doesn’t enforce any naming conventions but has some guidelines.
register and registerAsync
The register and registerAsync methods we’ve used in this article so far are supposed to configure a module for use only with the module that imports it.
To illustrate it, let’s look at the EmailSchedulingModule.
1import { Module } from '@nestjs/common';
2import EmailSchedulingService from './emailScheduling.service';
3import { EmailModule } from '../email/email.module';
4import EmailSchedulingController from './emailScheduling.controller';
5import { ConfigModule, ConfigService } from '@nestjs/config';
6
7@Module({
8 imports: [
9 EmailModule.registerAsync({
10 imports: [ConfigModule],
11 inject: [ConfigService],
12 useFactory: (configService: ConfigService) => ({
13 service: configService.get('EMAIL_SERVICE'),
14 user: configService.get('EMAIL_USER'),
15 password: configService.get('EMAIL_PASSWORD'),
16 }),
17 }),
18 ],
19 controllers: [EmailSchedulingController],
20 providers: [EmailSchedulingService],
21})
22export class EmailSchedulingModule {}Above, we provide the configuration for the EmailModule that we only want to use in the EmailSchedulingModule.
forRoot and forRootAsync
With forRoot and forRootAsync methods, we aim to configure a dynamic module once and reuse this configuration in multiple places. Therefore, it makes a lot of sense with global modules.
A great example is the TypeOrmModule module provided by NestJS.
1import { Module } from '@nestjs/common';
2import { TypeOrmModule } from '@nestjs/typeorm';
3import { ConfigModule, ConfigService } from '@nestjs/config';
4import Address from '../users/address.entity';
5
6@Module({
7 imports: [
8 TypeOrmModule.forRootAsync({
9 imports: [ConfigModule],
10 inject: [ConfigService],
11 useFactory: (configService: ConfigService) => ({
12 type: 'postgres',
13 username: configService.get('POSTGRES_USER'),
14 password: configService.get('POSTGRES_PASSWORD'),
15 entities: [Address],
16 autoLoadEntities: true,
17 // ...
18 }),
19 }),
20 ],
21})
22export class DatabaseModule {}forFeature and forFeatureAsync
With the forFeature and forFeatureAsync methods, we can alter the configuration specified using forRootAsync. Again, a good example is the TypeOrmModule.
1import { Module } from '@nestjs/common';
2import CategoriesController from './categories.controller';
3import CategoriesService from './categories.service';
4import Category from './category.entity';
5import { TypeOrmModule } from '@nestjs/typeorm';
6
7@Module({
8 imports: [TypeOrmModule.forFeature([Category])],
9 controllers: [CategoriesController],
10 providers: [CategoriesService],
11})
12export class CategoriesModule {}Above, we specify additional configuration using forFeature() that’s applicable only in the CategoriesModule.
Configurable module builder
Configuring a dynamic module can be difficult, especially with the asynchronous methods. Fortunately, NestJS has a ConfigurableModuleBuilder class that does much of the work for us. To use it, let’s create a separate file.
1import { ConfigurableModuleBuilder } from '@nestjs/common';
2import EmailOptions from './emailOptions.interface';
3
4export const {
5 ConfigurableModuleClass: ConfigurableEmailModule,
6 MODULE_OPTIONS_TOKEN: EMAIL_CONFIG_OPTIONS,
7} = new ConfigurableModuleBuilder<EmailOptions>().build();Now, we need our EmailModule to extend the ConfigurableEmailModule class.
1import { Module } from '@nestjs/common';
2import { ConfigurableEmailModule } from './email.module-definition';
3import EmailService from './email.service';
4
5@Module({
6 providers: [EmailService],
7 exports: [EmailService],
8})
9export class EmailModule extends ConfigurableEmailModule {}Thanks to the above, our EmailModule allows us to use both register and registerAsync classes.
For it to work as expected, we need to remember to use the EMAIL_CONFIG_OPTIONS constant that we got from the email.module-definition.ts file.
Extending auto-generated methods
If we need additional logic, we can extend the auto-generated methods. When doing that, the ConfigurableModuleAsyncOptions can come in handy.
1import { ConfigurableModuleAsyncOptions, DynamicModule, Module } from '@nestjs/common';
2import { ConfigurableEmailModule } from './email.module-definition';
3import EmailService from './email.service';
4import EmailOptions from './emailOptions.interface';
5
6@Module({
7 providers: [EmailService],
8 exports: [EmailService],
9})
10export class EmailModule extends ConfigurableEmailModule {
11 static register(options: EmailOptions): DynamicModule {
12 return {
13 // you can put additional configuration here
14 ...super.register(options),
15 };
16 }
17
18 static registerAsync(options: ConfigurableModuleAsyncOptions<EmailOptions>): DynamicModule {
19 return {
20 // you can put additional configuration here
21 ...super.registerAsync(options),
22 };
23 }
24}Using methods other than register and registerAsync
If we want to use methods other than register and registerAsync, we need to call the setClassMethodName function.
1import { ConfigurableModuleBuilder } from '@nestjs/common';
2import EmailOptions from './emailOptions.interface';
3
4export const {
5 ConfigurableModuleClass: ConfigurableEmailModule,
6 MODULE_OPTIONS_TOKEN: EMAIL_CONFIG_OPTIONS,
7} = new ConfigurableModuleBuilder<EmailOptions>()
8 .setClassMethodName('forRoot')
9 .build();Summary
In this article, we’ve gone through the idea of dynamic modules. To illustrate it, we implemented it manually and learned how it works under the hood. Then, we’ve learned how to use utilities built into NestJS that can simplify this process significantly. Dynamic modules are a handy feature that allows us to make our modules customizable while taking advantage of the dependency injection mechanism.