Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 42 ยท Advanced Dependency Injection

Dynamic Modules and Provider Scopes

Learn NestJS dynamic modules (forRoot, register, forRootAsync, global modules) and the DEFAULT, REQUEST and TRANSIENT provider scopes with their performance cost.

This lesson covers two ideas that finish the dependency-injection story. The first is the dynamic module: a module that accepts options when you import it, such as ConfigModule.forRoot({ isGlobal: true }) from the previous lesson. The second is the provider scope: how long an instance lives. By default one instance serves the whole application, but Nest can also create one per request or one per consumer, and that choice has real consequences for speed.

You need modules and custom providers as background. The Nest code below is read-only because the framework needs Node and npm. The runnable parts are stand-ins in plain JavaScript that apply the same rules, so you can see what a dynamic module returns and how many instances each scope creates.

Why modules need options

A static module is the same wherever it is imported. But a database module needs a connection URL, a mail module needs credentials, and a cache module needs a time-to-live. Providing those through a hard-coded constant would make the module impossible to reuse. A dynamic module solves it by exposing a static method that returns a module description built from your options.

TypeScript
import { DynamicModule, Module } from '@nestjs/common';

export interface GreetingOptions {
  greeting: string;
}

export const GREETING_OPTIONS = Symbol('GREETING_OPTIONS');

@Module({})
export class GreetingModule {
  static register(options: GreetingOptions): DynamicModule {
    return {
      module: GreetingModule,
      providers: [
        { provide: GREETING_OPTIONS, useValue: options },
        GreetingService,
      ],
      exports: [GreetingService],
    };
  }
}

module names the class, and the other properties (providers, exports, imports, controllers, global) are merged with what @Module() already declares: they extend it, they do not replace it. A consumer of the dynamic module imports the result of the call:

TypeScript
@Module({
  imports: [GreetingModule.register({ greeting: 'Hello' })],
})
export class AppModule {}

Inside GreetingService, the options arrive with @Inject(GREETING_OPTIONS), exactly like the token-based providers you already know.

Three method names, three meanings

forRoot Configure once, app-wide.
register Configure per importing module.
forFeature Add feature-specific pieces.

These are conventions, not rules enforced by Nest.

1 / 2

Naming conventions

Nest does not enforce method names, but the ecosystem agrees on them, and following them makes your modules feel familiar:

  • forRoot(): configure the module once for the whole application, usually in the root module. Examples: ConfigModule.forRoot(), TypeOrmModule.forRoot().
  • register(): configure the module for one importer. Several modules may import it with different options, and each gets its own configuration.
  • forFeature(): an already-configured root module gets extra, feature-specific content, such as the entities a feature module will use.

Async options with useFactory

Often the options are not known when the file is evaluated. A database URL may come from ConfigService, which itself is only ready after the container starts. The convention is a forRootAsync() variant that accepts a factory and the providers it needs:

TypeScript
MailModule.forRootAsync({
  imports: [ConfigModule],
  inject: [ConfigService],
  useFactory: (config: ConfigService) => ({
    host: config.getOrThrow<string>('SMTP_HOST'),
    port: config.get<number>('SMTP_PORT', 587),
  }),
})

Inside the module, forRootAsync() turns this into a normal custom provider: { provide: MAIL_OPTIONS, useFactory, inject }, and adds imports to the module description so that ConfigService is visible. Most official integrations support three async styles: useFactory (shown above), useClass (a class implementing an createOptions() method) and useExisting.

Writing both the sync and async variants by hand is repetitive, so Nest ships ConfigurableModuleBuilder. You describe the options type and it generates the base class and the options token:

TypeScript
import { ConfigurableModuleBuilder } from '@nestjs/common';

export const { ConfigurableModuleClass, MODULE_OPTIONS_TOKEN } =
  new ConfigurableModuleBuilder<MailOptions>().build();

@Module({ providers: [MailService], exports: [MailService] })
export class MailModule extends ConfigurableModuleClass {}

With that, MailModule.register(...) and MailModule.registerAsync(...) exist, and MailService injects the options with @Inject(MODULE_OPTIONS_TOKEN). The builder can rename the methods (for example to forRoot) and add extras such as an isGlobal flag; see its documentation for the exact options.

Global dynamic modules

Return global: true from the module description and the module's exports become available everywhere, without being imported by each feature. This is what isGlobal: true does in ConfigModule.forRoot(). The advice from the modules lesson still applies: use it for infrastructure such as configuration, logging and database access, and keep feature modules explicit.

TypeScript
static forRoot(options: LoggerOptions): DynamicModule {
  return {
    module: LoggerModule,
    global: true,
    providers: [{ provide: LOGGER_OPTIONS, useValue: options }, LoggerService],
    exports: [LoggerService],
  };
}

Stand-in: what a dynamic module returns

The first stand-in builds module descriptions like the ones above, without Nest. It merges a static definition with the description returned by register() or forRootAsync(), awaits an async factory, and then lists what each module ends up with. Real Nest does the merging inside its scanner; here it is a few lines.

JS Dynamic module descriptions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The static meta plays the role of @Module({...}); the call result extends it. The two register() calls give two separate option sets, which is how one module class can be configured differently by different importers. The async version waited for the factory.

Provider scopes

By default every provider is a singleton: Nest creates it once at startup and shares it for the life of the application (Scope.DEFAULT). That is the right choice for almost everything, including most services, repositories and clients. Two other scopes exist:

Scope Lifetime New instance when
DEFAULT the whole application never, after startup
REQUEST one incoming request (or message/event) each request, garbage-collected afterward
TRANSIENT one consumer every class that injects it gets its own copy

You set the scope in the decorator:

TypeScript
import { Injectable, Scope } from '@nestjs/common';

@Injectable({ scope: Scope.REQUEST })
export class RequestContext {
  userId?: string;
}

@Injectable({ scope: Scope.TRANSIENT })
export class TaskLogger {
  context = 'unknown';
}

For custom providers, put scope next to the recipe: { provide: X, useClass: Y, scope: Scope.TRANSIENT }. A request-scoped provider can inject the current request object with @Inject(REQUEST) (import REQUEST from @nestjs/core).

Scope bubbles up

Here is the part that surprises people. If a singleton depends on a request-scoped provider, it cannot remain a singleton, because it would hold a stale instance from one request. So the scope bubbles up the injection chain: the service becomes request-scoped, then the controller that injects that service becomes request-scoped, and so on. One request-scoped provider deep in the graph can turn a large part of your application into per-request objects. Transient scope does not bubble: a singleton that injects a transient provider gets its own private copy and stays a singleton.

The cost

Request-scoped providers are created and destroyed on every request, together with every provider that depends on them. That costs CPU and memory, and it adds up under load, so use them sparingly. They also come with caveats: lifecycle hooks such as onModuleInit are not called for them in the usual way. Prefer these alternatives first:

  • Pass the user id or tenant as a method argument from the controller to the service.
  • Store per-request context in Node's AsyncLocalStorage, which libraries such as nestjs-cls wrap, and keep the services as singletons.
  • Use a durable provider (durable: true with a ContextIdStrategy) in multi-tenant systems where many requests share a tenant, so the provider tree is built once per tenant rather than once per request.

Stand-in: counting instances per scope

The second stand-in is a miniature container that applies the three scopes and the bubbling rule, then handles three requests and counts how many instances of each class were created. Real Nest is more sophisticated (it analyses the dependency graph once, up front), but the counts show the same effect.

JS How many instances?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

AuditService is declared as a default singleton, yet it becomes request-scoped because it injects RequestContext, and UsersController follows because it injects AuditService. UsersService and Config stay singletons and are created once. Clock is transient, so each consumer gets a new one: here only AuditService consumes it, and AuditService is rebuilt per request.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the correct way for a dynamic module to receive options such as a connection URL?

    The static method returns a module description. Its properties are merged with the @Module() metadata, and the options are usually exposed through a token provider.
  2. 2. A controller injects a service that injects a Scope.REQUEST provider. What scope does the controller effectively have?

    A consumer of a request-scoped provider cannot be a singleton, so it becomes request-scoped too, along with everything above it in the chain.
  3. 3. Which is the usual convention for forRoot() versus register()?

    The names are only conventions, but most libraries follow them: forRoot for app-wide setup, register for per-importer configuration, forFeature for extras.
  4. 4. Which approach avoids request-scoped providers while still giving each request its own user context?

    AsyncLocalStorage keeps data per async call chain while services stay singletons. A global variable would leak between concurrent requests.

Summary

  • A dynamic module is a module with a static method (forRoot, register, forFeature, or ...Async) that returns a DynamicModule; its properties extend the @Module() metadata.
  • Async variants take useFactory and inject and are built from custom providers; ConfigurableModuleBuilder can generate them.
  • global: true in the returned description makes a module's exports available everywhere.
  • Providers are singletons by default; REQUEST creates one instance per request and TRANSIENT one per consumer.
  • Request scope bubbles up to every provider and controller that depends on it, and costs performance on every request.
  • Prefer method arguments, AsyncLocalStorage or durable providers to broad request scoping.

Next, put these tools to work by connecting your app to storage in Connecting to a Database.