We need to watch out for quite a few pitfalls when designing our architecture. One of them is the possibility of circular dependencies. In this article, we go through this concept in the context of Node.js modules and NestJS services. Circular dependencies in Node.js modules A circular dependency between Node.js modules happens when two files import each other. Let’s look into this straightforward example: one.js const { two } = require('./two'); const one = '1'; console.log('file one.js:', one, two); module.exports.one = one; two.js const { one } = require('./one'); const two = '2'; console.log('file two.js:', one, two); module.exports.two = two;After running node ./one.js, we see the following output: file two.js: undefined 2 file one.js: 1 2 (node:109498) Warning: Accessing non-existent property ‘one’ of module exports inside circular dependency (Use node --trace-warnings ... to show where the warning was created) We can see that a code containing circular dependencies can run but might result in unexpected results. The above code executes as follows: one.js executes, and imports two.js, two.js executes, and imports one.js, to prevent an infinite loop, two.js loads an unfinished copy of one.js, this is why the one variable in two.js is undefined, two.js finishes executing, and its exported value reaches one.js, one.js continues running and contains all valid values. The above example allows us to understand how Node.js reacts to circular dependencies. Circular dependencies are often a sign of a bad design, and we should avoid them when possible. Detecting circular dependencies using ESLint The provided code example makes it very obvious that there is a circular dependency between files. It is not always that apparent, though. Fortunately, ESLint can help us detect such dependencies. To do that, we need the eslint-plugin-import package.npm install eslint-plugin-importThe rule that we want is called import/no-cycle, and it ensures that no circular dependencies are present between our files. In our NestJS project, we would set the configuration in the following way: .eslintrc.js module.exports = { "parser": "@typescript-eslint/parser", "plugins": [ "import", // ... ], "extends": [ "plugin:import/typescript", // ... ], "rules": { "import/no-cycle": 2, // ... }, // ... }; Circular dependencies in NestJS Besides circular dependencies between Node.js modules, we might also run into this issue when working with NestJS modules. In part 55 of this series, we’ve implemented a feature of uploading files to the server. Let’s expand on it to create a case with a circular dependency. localFiles.service.js import { Injectable, NotFoundException } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import LocalFile from './localFile.entity'; import { UsersService } from '../users/users.service'; @Injectable() class LocalFilesService { constructor( @InjectRepository(LocalFile) private localFilesRepository: Repository, private usersService: UsersService ) {} async getUserAvatar(userId: number) { const user = await this.usersService.getById(userId); return this.getFileById(user.avatarId); } async saveLocalFileData(fileData: LocalFileDto) { const newFile = await this.localFilesRepository.create(fileData) await this.localFilesRepository.save(newFile); return newFile; } async getFileById(fileId: number) { const file = await this.localFilesRepository.findOne(fileId); if (!file) { throw new NotFoundException(); } return file; } } export default LocalFilesService; users.service.js import { HttpException, HttpStatus, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import User from './user.entity'; import LocalFilesService from '../localFiles/localFiles.service'; @Injectable() export class UsersService { constructor( @InjectRepository(User) private usersRepository: Repository, private localFilesService: LocalFilesService ) {} async getById(id: number) { const user = await this.usersRepository.findOne({ id }); if (user) { return user; } throw new HttpException('User with this id does not exist', HttpStatus.NOT_FOUND); } async addAvatar(userId: number, fileData: LocalFileDto) { const avatar = await this.localFilesService.saveLocalFileData(fileData); await this.usersRepository.update(userId, { avatarId: avatar.id }) } // ... } Solving the issue using forward referencing In our case, the LocalFilesService needs the UsersService and the other way around. Let’s look into how our modules look so far. localFiles.module.ts import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule } from '@nestjs/config'; import LocalFile from './localFile.entity'; import LocalFilesService from './localFiles.service'; import LocalFilesController from './localFiles.controller'; import { UsersModule } from '../users/users.module'; @Module({ imports: [ TypeOrmModule.forFeature([LocalFile]), ConfigModule, UsersModule ], providers: [LocalFilesService], exports: [LocalFilesService], controllers: [LocalFilesController] }) export class LocalFilesModule {} users.module.ts import { Module } from '@nestjs/common'; import { UsersService } from './users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import User from './user.entity'; import { UsersController } from './users.controller'; import { ConfigModule } from '@nestjs/config'; import { LocalFilesModule } from '../localFiles/localFiles.module'; @Module({ imports: [ TypeOrmModule.forFeature([User]), ConfigModule, LocalFilesModule, // ... ], providers: [UsersService], exports: [UsersService], controllers: [UsersController] }) export class UsersModule {}Above, we see that LocalFilesModule imports the UsersModule and vice versa. Running the application with the above configuration causes an error, unfortunately. [ExceptionHandler] Nest cannot create the LocalFilesModule instance. The module at index [2] of the LocalFilesModule “imports” array is undefined. Potential causes: – A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency – The module at index [2] is of type “undefined”. Check your import statements and the type of the module. Scope [AppModule -> PostsModule -> UsersModule] Error: Nest cannot create the LocalFilesModule instance. The module at index [2] of the LocalFilesModule “imports” array is undefined. A workaround for the above is to use forward referencing. Thanks to it, we can refer to a module before NestJS initializes it. To do that, we need to use the forwardRef function. localFiles.module.ts import { Module, forwardRef } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { ConfigModule } from '@nestjs/config'; import LocalFile from './localFile.entity'; import LocalFilesService from './localFiles.service'; import LocalFilesController from './localFiles.controller'; import { UsersModule } from '../users/users.module'; @Module({ imports: [ TypeOrmModule.forFeature([LocalFile]), ConfigModule, forwardRef(() => UsersModule), ], providers: [LocalFilesService], exports: [LocalFilesService], controllers: [LocalFilesController] }) export class LocalFilesModule {} users.module.ts import { Module, forwardRef } from '@nestjs/common'; import { UsersService } from './users.service'; import { TypeOrmModule } from '@nestjs/typeorm'; import User from './user.entity'; import { UsersController } from './users.controller'; import { ConfigModule } from '@nestjs/config'; import { LocalFilesModule } from '../localFiles/localFiles.module'; @Module({ imports: [ TypeOrmModule.forFeature([User]), ConfigModule, forwardRef(() => LocalFilesModule), // ... ], providers: [UsersService], exports: [UsersService], controllers: [UsersController] }) export class UsersModule {}Doing the above solves the issue of circular dependencies between our modules. Unfortunately, we still need to fix the problem for services. We need to use the forwardRef function and the @Inject() decorator to do that. localFiles.service.ts import { forwardRef, Inject, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import LocalFile from './localFile.entity'; import { UsersService } from '../users/users.service'; @Injectable() class LocalFilesService { constructor( @InjectRepository(LocalFile) private localFilesRepository: Repository, @Inject(forwardRef(() => UsersService)) private usersService: UsersService ) {} // ... } export default LocalFilesService; users.service.ts import { forwardRef, Inject, Injectable, } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import User from './user.entity'; import LocalFilesService from '../localFiles/localFiles.service'; @Injectable() export class UsersService { constructor( @InjectRepository(User) private usersRepository: Repository, @Inject(forwardRef(() => LocalFilesService)) private localFilesService: LocalFilesService ) {} // ... }Doing all of the above causes our services to function correctly despite the circular dependencies. Circular dependencies between TypeORM entities We might also run into issues with circular dependencies with TypeORM entities. For example, this might happen when dea