Circular Dependencies and forwardRef

When Two Classes Need Each Other

OrdersService needs PaymentsService to charge the customer, and PaymentsService needs OrdersService to mark the order paid. NestJS cannot create either first.

Example

npm run start:dev

Example output

[Nest] ERROR [ExceptionHandler] Nest cannot create the OrdersModule instance.
A circular dependency between modules. Use forwardRef() to avoid it.
Scope [AppModule -> OrdersModule -> PaymentsModule]

forwardRef as an Escape Hatch

Wrap the reference in forwardRef() on both sides (module imports and constructor injection):

// orders.module.ts
@Module({ imports: [forwardRef(() => PaymentsModule)], providers: [OrdersService], exports: [OrdersService] })
export class OrdersModule {}

// payments.module.ts
@Module({ imports: [forwardRef(() => OrdersModule)], providers: [PaymentsService], exports: [PaymentsService] })
export class PaymentsModule {}

// orders.service.ts
@Injectable()
export class OrdersService {
  constructor(@Inject(forwardRef(() => PaymentsService)) private readonly payments: PaymentsService) {}
}

Tip: A circular dependency is usually a design smell. Better fixes: move the shared logic into a third service, or use events (@nestjs/event-emitter): PaymentsService emits payment.captured and OrdersService listens. Then neither imports the other.