Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 42 ยท Advanced Dependency Injection

Custom Providers

Learn NestJS custom providers: useClass, useValue, useFactory and useExisting, injection tokens, @Inject, optional dependencies, and how to swap providers.

So far every provider in this tutorial was a class listed in a module's providers array. That shorthand, providers: [CatsService], is only one of several ways to tell Nest what to inject. Real applications also need to inject a constant (an API key), an object built at startup (a database connection that needs an async handshake), a different class in tests (a fake mailer), or a second name for an existing provider. For all of these Nest has custom providers.

A custom provider is an object that says three things: the token (what a consumer asks for), the recipe (how Nest produces the value) and, optionally, the dependencies of that recipe. This lesson builds on providers and dependency injection and modules. The real Nest code is read-only, because the framework needs Node and npm. The runnable parts are stand-ins: a small registry in plain JavaScript that follows the same rules, so you can watch tokens and recipes work. It is not Nest, and it says where it simplifies.

The shorthand and its long form

This line:

TypeScript
@Module({
  providers: [CatsService],
})
export class CatsModule {}

is a short way of writing:

TypeScript
@Module({
  providers: [{ provide: CatsService, useClass: CatsService }],
})
export class CatsModule {}

provide is the injection token. useClass is the recipe: "when someone asks for this token, instantiate this class and resolve its constructor parameters". Once you see the long form, the other recipes are just different keys next to provide.

One token, four recipes

useClass Nest creates an instance of a class.
useValue You hand over a ready-made value.
useFactory A function builds the value.
useExisting A second name for another token.

Consumers only ever see the token.

1 / 2

useValue: inject a constant or a ready object

useValue gives Nest a value that already exists. It is ideal for configuration objects, constants, and mocks in tests:

TypeScript
const mockMailer = {
  send: (to: string) => ({ queued: true, to }),
};

@Module({
  providers: [{ provide: 'MAILER', useValue: mockMailer }],
})
export class TestMailModule {}

Nest does not clone the value and does not call anything on it: the same object is handed to every consumer. That is also why useValue suits tests so well: Test.createTestingModule() can replace a real provider with a fake using the same token, and the class under test never notices.

Tokens: classes, strings and symbols

A class works as a token because a class is a value at runtime and TypeScript can emit its type for the constructor parameter. Interfaces and type aliases do not exist at runtime, so you cannot use them as a token. If you write constructor(private mailer: Mailer) where Mailer is an interface, Nest sees nothing it can look up. The fix is a separate token and the @Inject() decorator:

TypeScript
export const MAILER = Symbol('MAILER');

export interface Mailer {
  send(to: string, body: string): Promise<void>;
}

@Injectable()
export class WelcomeService {
  constructor(@Inject(MAILER) private readonly mailer: Mailer) {}
}

Strings work as tokens too ('MAILER'), but they can collide, and a typo in one place is found only at startup. A Symbol kept in a constants file cannot collide and gives your editor something to autocomplete. Whatever you choose, define the token once and import it everywhere.

When a token is not a class, you must also list it in exports by token (or export the whole provider object) if other modules need it:

TypeScript
@Module({
  providers: [{ provide: MAILER, useClass: SmtpMailer }],
  exports: [MAILER],
})
export class MailModule {}

useClass: choose the implementation

useClass can point to a different class than the token. That is how you pick an implementation by environment, or give a service a default and an override:

TypeScript
const mailerProvider = {
  provide: MAILER,
  useClass: process.env.NODE_ENV === 'production' ? SmtpMailer : ConsoleMailer,
};

@Module({ providers: [mailerProvider], exports: [MAILER] })
export class MailModule {}

The class is still created by Nest, so its own constructor dependencies are injected as usual. The decision is made once, at startup, not on each request.

useFactory: build the value with code

When creating the value takes logic, use a factory. Its arguments are the providers named in inject, in the same order, and it may be async; Nest waits for the promise before it starts listening:

TypeScript
@Module({
  providers: [
    {
      provide: 'DB_CONNECTION',
      useFactory: async (settings: AppSettings) => {
        const connection = createConnection(settings.databaseUrl);
        await connection.connect();
        return connection;
      },
      inject: [AppSettings],
    },
  ],
  exports: ['DB_CONNECTION'],
})
export class DatabaseModule {}

An entry in inject can also be an object, { token: 'FEATURE_FLAGS', optional: true }. If nothing is registered for an optional token, the factory receives undefined instead of the app failing to boot. In a class, the same idea is the @Optional() decorator in front of a constructor parameter.

Factories are the foundation of the "async options" pattern you will meet in dynamic modules and of database setup in Connecting to a Database.

useExisting: an alias

useExisting makes one token resolve to the instance of another. Nothing new is created:

TypeScript
const loggerAlias = { provide: 'AliasedLogger', useExisting: LoggerService };

Both tokens now give the same object. This is useful when you migrate a name, or when one class should answer to a broad token (NOTIFIER) and to its own class token.

Stand-in: a registry that understands the recipes

The first stand-in is a tiny dependency registry. It reads the same four recipe shapes, resolves dependencies by token, caches each instance (so providers behave as singletons), and detects a missing token and a cycle. Real Nest additionally scans decorator metadata and respects module boundaries; here every provider lives in one flat list, and constructor dependencies are declared in a static inject array instead of coming from @Inject() metadata.

JS The four recipes in one registry

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

No output.

The output shows the value recipe (SETTINGS), the class recipe with injected dependencies, a factory that depends on another provider, and an alias that returns the same instance. The last lines show the kind of failure you get when a token has no provider. Nest's own message is longer, but it has the same shape: who needed what, and where.

Stand-in: swapping and optional dependencies

The second stand-in shows why tokens are so valuable. A service asks for MAILER and an optional FEATURE_FLAGS. We build the container twice, once with the real recipe and once with a fake, without touching the service. This is the idea behind overriding providers in tests, which you will use for real in Testing Nest Applications.

JS Same service, different providers

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

No output.

WelcomeService never changed. Only the recipe behind MAILER did. The optional FEATURE_FLAGS token had no provider in the first two runs, and the service simply used its default.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can't you use a TypeScript interface directly as an injection token?

    Types vanish when TypeScript compiles to JavaScript. Use a Symbol or string constant as the token and put @Inject(TOKEN) on the constructor parameter.
  2. 2. Which recipe would you choose to inject an object that must be created with an await at startup?

    A factory may be async. Nest waits for it to finish before the application starts accepting requests, and passes it the providers listed in inject.
  3. 3. What does useExisting do?

    It is an alias. Both tokens return the same object, and nothing new is instantiated.
  4. 4. A custom provider uses a Symbol token and lives in MailModule. What else is needed so UsersModule can inject it?

    Module visibility rules still apply. Export the token (or the provider object) from the owner and import the owner module in the consumer.

Summary

  • A provider is { provide: token, <recipe> }; providers: [Cls] is shorthand for useClass: Cls.
  • useValue hands over an existing value, useClass picks an implementation, useFactory builds with code (sync or async, with inject), useExisting aliases another token.
  • Interfaces cannot be tokens: use a Symbol or string and @Inject(TOKEN).
  • @Optional() or { token, optional: true } lets a dependency be missing without breaking startup.
  • Non-class tokens must be exported by token for other modules to use them.
  • Swapping a recipe, as tests do, never requires changing the consumer.

Next, use these tools to feed settings into your app safely in Configuration and Environment.