In NestJS, how do useClass, useValue, useFactory and useExisting providers differ, and when must a consumer use @Inject() with a token?
answer
- provide plus one use key
- shorthand means useClass
- factory arguments follow inject order
- interfaces vanish at runtime
basics
~20 sEach NestJS custom provider maps a token to a value: useClass instantiates a class, useValue registers a ready object, useFactory returns what a function builds from its inject list, and useExisting aliases another token. Non-class tokens need @Inject(token).
solid answer
~40 s`providers: [PaymentsService]` is shorthand for `{ provide: PaymentsService, useClass: PaymentsService }`; the long form lets the token and the implementation differ. `useClass` chooses the class Nest instantiates, for example per environment. `useValue` registers an existing object or a test double as is. `useFactory` calls a function, sync or async, passing the providers listed in `inject` in the same order; an entry `{ token, optional: true }` resolves to `undefined` when missing. `useExisting` points a second token at an existing provider, so both resolve to the same instance. Injection by constructor type works only for runtime classes, abstract classes included; a string or `Symbol` token, the usual choice for an interface, needs `@Inject(TOKEN)` on the parameter.
code
typescript · 39 linesimport { Inject, Injectable, Module } from '@nestjs/common';
export const PAYMENT_GATEWAY = Symbol('PAYMENT_GATEWAY');
export interface PaymentGateway {
charge(orderId: string, cents: number): Promise<string>;
}
@Injectable()
export class GatewaySettings {
readonly baseUrl = process.env.GATEWAY_URL ?? 'http://localhost:4000';
}
class HttpPaymentGateway implements PaymentGateway {
constructor(private readonly baseUrl: string) {}
async charge(orderId: string, cents: number): Promise<string> {
return `${this.baseUrl}/charges/${orderId}?cents=${cents}`;
}
}
@Injectable()
export class CheckoutService {
constructor(@Inject(PAYMENT_GATEWAY) private readonly gateway: PaymentGateway) {}
}
@Module({
providers: [
GatewaySettings,
{
provide: PAYMENT_GATEWAY,
useFactory: (settings: GatewaySettings) => new HttpPaymentGateway(settings.baseUrl),
inject: [GatewaySettings],
},
{ provide: 'LEGACY_GATEWAY', useExisting: PAYMENT_GATEWAY },
CheckoutService,
],
exports: [PAYMENT_GATEWAY],
})
export class PaymentsModule {}go deeper
Know that providers: [X] is shorthand for provide plus useClass, and that a string or Symbol token is injected with @Inject(token).
Explain all four kinds, the positional inject list, optional inject entries and async factories, and why an interface cannot be a token.
Pick tokens deliberately, Symbols or abstract classes over strings, and use factories for async setup whose failure should stop startup rather than surface later.
Set a team convention for tokens and contracts so swapping implementations or test doubles never requires touching consumers.
## Tokens and the shorthand Nest's injector stores providers under **tokens**. A token is the key a consumer asks for; the provider definition says how to produce the value. When you write `providers: [PaymentsService]`, Nest expands it to: ```typescript { provide: PaymentsService, useClass: PaymentsService } ``` The class is both the token and the implementation. A **custom provider** writes the object form yourself, so that the token and the value can differ. The `provide` key is required, and one of the four `use` keys defines the value; a definition with none of them fails at bootstrap with `InvalidProviderException`. ## The four provider kinds | Kind | What Nest does | Typical use | |---|---|---| | `useClass` | instantiates the given class and resolves its constructor dependencies | choose an implementation per environment; bind an abstract class token to a concrete class | | `useValue` | registers the given value unchanged, with no instantiation | constants, an already-built client object, a mock in a test module | | `useFactory` | calls a function and registers its return value, awaiting a promise | values that need computation, other providers or async setup | | `useExisting` | makes the token an alias of another token | expose one instance under a second name | Two details matter for interviews: - **`useExisting` creates nothing.** Under the default singleton scope, the alias and the original resolve to the same object. Registering the same class twice with `useClass` would create two instances. - **`useValue` is not instantiated.** If you pass a class to `useValue`, consumers receive the class itself, not an instance of it. ## Factory providers in detail `useFactory` is the most flexible kind, and it has its own rules: 1. The `inject` array lists tokens Nest resolves first; their instances are passed to the factory **as positional arguments, in the same order**. Names of the function's parameters play no part. 2. An `inject` entry can be `{ token: 'RETRY_POLICY', optional: true }`. If nothing provides that token, the argument is `undefined` instead of a bootstrap failure. 3. The factory may be `async`. Nest awaits the promise during bootstrap before building anything that depends on the token, which is why factories are the usual place to open a connection. An error thrown by the factory stops application startup. 4. The object can also carry `scope` (for example `Scope.REQUEST`) and, for request scope, `durable`. ## Choosing the token Constructor injection by type works because TypeScript emits each constructor parameter's type as runtime metadata, and Nest looks that metadata up as a token. That gives four practical choices: - **A class.** The default: inject by type, no decorator needed. - **An abstract class.** It exists at runtime, so it can be the contract and the token at once: `{ provide: PaymentGateway, useClass: HttpPaymentGateway }` and a plain `constructor(private gateway: PaymentGateway)`. - **A string.** Simple, but two unrelated providers can collide on the same string. - **A `Symbol`.** Each symbol is unique; export it from one file and reuse it where the provider is registered and injected. A TypeScript **interface** or type alias is erased during compilation, so `constructor(private gateway: PaymentGateway)` with an interface leaves Nest no token and bootstrap fails with an unresolved-dependency error. The same happens when a class is imported with `import type`. For any non-class token, the consumer writes `@Inject(TOKEN)` on the parameter. ## Common mistakes - **Mismatched `inject` order.** Swapping two entries in `inject` silently swaps the factory's arguments; TypeScript types on the factory parameters do not reorder anything at runtime. - **Two string tokens with the same text.** Two libraries registering `'CONFIG'` collide; a `Symbol` exported from one file avoids that. - **Forgetting `@Inject()` for a non-class token.** Without it Nest falls back to the emitted parameter type, which for an interface or type alias carries no usable token. - **Using `useValue` for something that needs dependencies.** A value is registered as is, so nothing gets injected into it; switch to `useFactory` with `inject` or to `useClass`. ## Visibility and export A custom provider belongs to its declaring module like any other. To share it, list it in `exports`, either by its token (`exports: [PAYMENT_GATEWAY]`) or by the same provider object. Consumers in other modules then import that module and inject the token with `@Inject()`.
- With useExisting, do the alias and the original token resolve to the same object?Yes, for the default singleton scope. `useExisting` registers no new instance; it points the second token at the first provider, so both injections receive one object. Registering the class again with `useClass` under a new token would instead create a second instance.
- Why does constructor(private gateway: PaymentGateway) fail when PaymentGateway is an interface?Nest resolves by the parameter types TypeScript emits as runtime metadata, and interfaces are erased, so there is no token to look up and bootstrap fails with an unresolved-dependency error. Register the implementation under a string or `Symbol` token and inject with `@Inject(TOKEN)`, or turn the contract into an abstract class.
- Can a factory provider be async, and what happens if it throws?Yes. `useFactory` may return a promise, and Nest awaits it during bootstrap before instantiating anything that depends on that token. If the factory throws or its promise rejects, application startup fails with that error, so the app never runs with a half-built dependency.
- useValue makes Nest instantiate the class you pass to it.
- A TypeScript interface can serve as an injection token by type.
- useExisting creates a second, independent instance under the new token.
- Factory arguments are matched to inject entries by parameter name.
- A string token can be injected by type without @Inject().