🦅 NestJS Intermediate

How does NestJS handle circular dependencies?

Answer

Circular dependencies occur when Module A imports Module B and Module B imports Module A, or when Service A injects Service B which injects Service A. NestJS has two solutions. ForwardRef for modules: imports: [forwardRef(() => CatsModule)] — the forwardRef() function tells NestJS to resolve the reference lazily. ForwardRef for providers: @Inject(forwardRef(() => CatsService)) private catsService: CatsService — both services must use forwardRef(). While these work, circular dependencies indicate a design issue. Refactoring to extract shared logic into a third module/service that both can import is the preferred long-term solution. Avoid circular dependencies by following the dependency rule: modules lower in the hierarchy should not depend on modules higher up.