In a NestJS app, OrdersService and PaymentsService inject each other and bootstrap fails. What does Nest report, and how does forwardRef() resolve it?
answer
- two classes, each in the other's constructor
- undefined at decoration time
- both sides, not one
- modules need it in imports too
- factories cannot be cyclic
basics
~20 sNestJS reports a CircularDependencyException, or an undefined dependency at some index when a file-level import cycle hides a class. Wrapping each side's token in @Inject(forwardRef(() => Other)) lets Nest resolve both; module cycles use forwardRef() in imports.
solid answer
~40 sWhen two providers name each other in their constructors, Nest cannot build either first. It reports `A circular dependency has been detected`, or, when an import cycle between the files leaves one class `undefined` while the decorators run, a `Nest can't resolve dependencies` error with a `?` at that index. Barrel `index.ts` files are a common cause. The fix in Nest is `@Inject(forwardRef(() => PaymentsService))` on one side and the mirror on the other; between modules, `imports: [forwardRef(() => PaymentsModule)]` on both. Instantiation order is then indeterminate, so neither constructor may call the other. Cycles between factory providers are not supported, and with request-scoped providers a dependency can end up `undefined`. `ModuleRef` lookup or extracting the shared logic are the alternatives.
code
typescript · 13 linesimport { Module, forwardRef } from '@nestjs/common';
import { OrdersService } from './orders.service.js';
import { PaymentsModule } from './payments.module.js';
@Module({
imports: [forwardRef(() => PaymentsModule)],
providers: [OrdersService],
exports: [OrdersService],
})
export class OrdersModule {}
// payments.module.ts mirrors it:
// imports: [forwardRef(() => OrdersModule)], providers: [PaymentsService], exports: [PaymentsService]go deeper
Recognise a circular dependency as two classes needing each other, and remember forwardRef() is applied on both sides.
Explain the CircularDependencyException and undefined-at-index symptoms, why barrel files cause them, and how forwardRef() works for providers and for modules.
Know the limits: indeterminate instantiation order, no support for factory cycles, request-scoped cycles yielding undefined, and when ModuleRef or extraction beats forwardRef().
Treat every forwardRef() as a design smell to track, and push teams towards extracting shared logic or one-way notifications instead.
## What a cycle looks like to Nest A **circular dependency** exists when class A needs class B and class B needs class A. In NestJS it can happen between **providers** (constructor injection) and between **modules** (`imports`). Nest builds providers bottom-up: to construct `OrdersService` it must first construct everything in its constructor. If that chain leads back to `OrdersService`, there is no valid first step. ## The errors you see The symptom depends on where the cycle is detected: - **Both classes are defined, but each injects the other.** The injector throws `CircularDependencyException`: "A circular dependency has been detected ... Please, make sure that each side of a bidirectional relationships are decorated with "forwardRef()"". The same message notes that cycles between custom providers such as factories are not supported, since a function cannot be called more than once. - **A file-level import cycle.** If `orders.service.ts` and `payments.service.ts` import each other, in a CommonJS build one class can still be `undefined` when TypeScript emits the other's parameter metadata (an ES-module build can fail earlier, with the language's own error for reading a binding before it is initialised). Nest then reports `Nest can't resolve dependencies of the OrdersService (?)` with a hint that the dependency at that index is undefined at runtime. - **A module cycle.** When two module files import each other, one module reference can be `undefined` and Nest throws `UndefinedModuleException`, saying the module at index N of the `imports` array is undefined and suggesting `forwardRef()`. The docs single out **barrel files** (`index.ts` re-exporting a folder) as a frequent hidden cause, especially when a file imports its own folder's barrel. Import module and provider classes from their files directly. ## Fixing provider cycles with forwardRef() `forwardRef()` from `@nestjs/common` wraps the class in a function that Nest calls later, once both classes exist: ```typescript @Injectable() export class OrdersService { constructor( @Inject(forwardRef(() => PaymentsService)) private readonly payments: PaymentsService, ) {} } @Injectable() export class PaymentsService { constructor( @Inject(forwardRef(() => OrdersService)) private readonly orders: OrdersService, ) {} } ``` Rules that come with it: 1. Apply it on **both** sides of the relationship, as the documentation and the error message both instruct. 2. The **order of instantiation is indeterminate**. Neither constructor may call a method on the other; use the reference later, inside ordinary methods. 3. Cycles involving `Scope.REQUEST` providers can leave a dependency `undefined`; avoid them rather than patch them. 4. Cycles between **factory** providers (`useFactory`) cannot be solved this way. ## Fixing module cycles Module cycles use the same helper inside `imports`, on both modules: | Module | `imports` entry | |---|---| | `OrdersModule` | `forwardRef(() => PaymentsModule)` | | `PaymentsModule` | `forwardRef(() => OrdersModule)` | Each module still has to export the provider the other one injects; `forwardRef()` defers the reference, it does not bypass encapsulation. A provider cycle that crosses modules usually needs both: `forwardRef()` in the two `imports` arrays and `@Inject(forwardRef(...))` in the two constructors. ## Alternatives to forwardRef() - **`ModuleRef` lookup.** Inject `ModuleRef` on one side and fetch the other provider with `moduleRef.get(PaymentsService)` when a method runs, so the constructor cycle disappears. Add `{ strict: false }` when the provider lives in another module. - **Extract the shared part.** Often each service needs only a small piece of the other. Moving that piece into a third provider that both inject removes the cycle outright and is usually the cleanest outcome. - **Turn one direction into a notification.** If `PaymentsService` only needs to tell orders that a payment settled, an event emitted from one side and handled on the other removes the constructor dependency. ## Why cycles appear in Nest codebases Cycles rarely start as a design decision. Typical paths: - Two feature services grow features that each need a small piece of the other, such as orders asking payments to charge and payments asking orders to mark an order paid. - A shared `index.ts` barrel lets a file import its own folder, so the module loader evaluates files in a different order than the injector expects. - A module re-exports a sibling for convenience, and the sibling later imports it back. Each `forwardRef()` added to silence the error makes the next cycle easier to introduce, which is why many teams treat it as a temporary measure and track it. ## How to investigate - Read which class the error names and which index carries the `?`. - Check the files for mutual imports and barrel re-exports before reaching for `forwardRef()`. - Set `NEST_DEBUG` to log the injector's lookups during startup.
- With forwardRef() on both sides, can OrdersService call a PaymentsService method from its constructor?It should not. The docs state that the order of instantiation is indeterminate, so the other instance may not be ready when a constructor runs. Store the reference and use it in ordinary methods, which run after bootstrap has wired both sides.
- Two factory providers each list the other's token in inject. Will forwardRef() fix that?No. Nest's circular-dependency message says cycles between custom providers such as factories are not supported, because a factory function cannot be called more than once. Break the cycle by moving the shared piece into a third provider, or turn one factory into a class provider that looks the other up lazily.
- forwardRef() on one side of the relationship is enough.
- forwardRef() guarantees which constructor runs first.
- Nest silently injects undefined into both services when they inject each other.
- forwardRef() in imports means the other module no longer needs to export anything.
- Factory providers can form a cycle as long as forwardRef() wraps their tokens.