← Back to list

Creating dynamic modules in nestjs

So, nestjs has two types of modules, Static and Dynamic modules. Say for example, to create a user module and book module, I simply create…

Samin karki · 2023-09-16 18:37 · 18 claps · 2.1 min read
#nestjs #typescript #dynamic-module
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Creating dynamic modules in nestjs

So, nestjs has two types of modules, Static and Dynamic modules. Say for example, to create a user module and book module, I simply create two modules, services, controllers and other necessary things for each. I register the module in app module and I am done.

Image from official nestjs docs

Image from official nestjs docs

What if I want to add csv file upload to both modules? Should I write csv parser for both modules? Nah. I think the better option would be to create another module, lets name it csv-parser and store the core csv parsing logic here and expose a parse function which would be similar for both modules. The parse method would take the csv file, the list of allowed headers in csv file, the validation logic for each file, the output formatter function for data. (Wow, a lot of things are dynamic, aren’t they? Only the parsing functionality seems same along with error handling logic and data-invalid logic.)

How will I use the csv-parser module? Importing the csv-parser module in each module and passing these dynamic values(allowed headers, validation functions, row parsing logic etc) every time I call a parser function from csv-parser module.

Did I just make my module dynamic?

I mean apart from passing all these dynamic values each time I call the csv-parser module’s parse method. Its pretty static.

The module is still static for csv parsing. I am just passing bunch of dynamic values to make the module dynamic. The csv-parser module is still static.

“Using dynamic module features, we can make our configuration module dynamic so that the consuming module can use an API to control how the configuration module is customized at the time it is imported.” — as written in official nestjs documentation. We’re not customizing the module at the time of import now, are we? That makes our module static.

To make the module dynamic, I updated csv-parser module by adding a static method register to csv-parser.module.ts and removing anything written in Module decorator and set it to empty object.

@Module({})
export class CsvParserModule {
  static register(options: Record<string, any>): DynamicModule {
    return {
      module: CsvParserModule,
      providers: [
        {
          provide: 'CONFIG_OPTIONS',
          useValue: options,
        },
        CsvParserService,
      ],
      exports: [CsvParserService],
    };
  }
}

The service that gets injected with options is written as

@Injectable()
export class CsvParserService {
  private readonly allowedHeaders: Array<string>;
  private readonly validatorFn: ()=>boolean;
  private readonly transformerFn: ()=>void;

  constructor(@Inject('CONFIG_OPTIONS') private options: Record<string, any>) {
    const {allowedHeaders, validatorFn, transformerFn} = options;
    this.allowedHeaders = allowedHeaders;
    this.validatorFn = validatorFn;
    this.transformerFn = transformerFn;
  }
}

And while importing, you just do this… (note that I am importing on app module)

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CsvParserModule } from './csv-parser/csv-parser.module';
import {validatorFn, transformerFn} from "./utilities"
@Module({
  imports: [CsvParserModule.register({ allowedHeaders: [], validatorFn, transformerFn})],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

And you can start using the module inside. You can use it wherever you like with different configurations. And thats all.


메타데이터
post_id
d53ba549f433
slug
creating-dynamic-modules-in-nestjs-d53ba549f433
url
https://medium.com/@samn.krki/creating-dynamic-modules-in-nestjs-d53ba549f433
canonical_url
https://medium.com/@samn.krki/creating-dynamic-modules-in-nestjs-d53ba549f433
author_url
https://medium.com/@samn.krki
status
ok
fetched_at
2026-07-24 23:44:46