How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
NestJS · TypeScript/React

Fix Error: A circular dependency has been detected. Please, make sure that each side of a bidirectional relationship is decorated with "forwardRef()". in NestJS

This error occurs when two or more NestJS modules or providers depend on each other, creating a circular import chain that the injector cannot resolve. Fix it by using forwardRef() on both sides of the circular dependency or by refactoring to extract shared logic into a separate module.

Reading the Stack Trace

Error: A circular dependency has been detected. Please, make sure that each side of a bidirectional relationship is decorated with "forwardRef()". at Injector.resolveComponentInstance (node_modules/@nestjs/core/injector/injector.js:204:19) at resolveParam (node_modules/@nestjs/core/injector/injector.js:128:38) at async Promise.all (index 0) at Injector.resolveConstructorParams (node_modules/@nestjs/core/injector/injector.js:143:27) at Injector.loadInstance (node_modules/@nestjs/core/injector/injector.js:52:13) at Injector.loadProvider (node_modules/@nestjs/core/injector/injector.js:74:9) at async Promise.all (index 4) at InstanceLoader.createInstancesOfProviders (node_modules/@nestjs/core/injector/instance-loader.js:44:9) at InstanceLoader.createInstances (node_modules/@nestjs/core/injector/instance-loader.js:29:9) at InstanceLoader.createInstancesOfDependencies (node_modules/@nestjs/core/injector/instance-loader.js:16:9)

Here's what each line means:

Common Causes

1. Two services injecting each other

ServiceA depends on ServiceB and ServiceB depends on ServiceA, creating a direct circular reference.

@Injectable()
export class OrderService {
  constructor(private userService: UserService) {}
}

@Injectable()
export class UserService {
  constructor(private orderService: OrderService) {}
}

2. Two modules importing each other

ModuleA imports ModuleB and ModuleB imports ModuleA without using forwardRef.

@Module({ imports: [UserModule] })
export class OrderModule {}

@Module({ imports: [OrderModule] })
export class UserModule {}

3. Indirect circular chain through a third module

ModuleA imports ModuleB, ModuleB imports ModuleC, and ModuleC imports ModuleA.

@Module({ imports: [ModuleB] }) export class ModuleA {}
@Module({ imports: [ModuleC] }) export class ModuleB {}
@Module({ imports: [ModuleA] }) export class ModuleC {} // Circular!

The Fix

Use @Inject(forwardRef(() => Service)) on both sides of the circular dependency so NestJS can lazily resolve the references. Also apply forwardRef() in the module imports. For a cleaner solution, consider extracting shared logic into a third service.

Before (broken)
// order.service.ts
import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';

@Injectable()
export class OrderService {
  constructor(private userService: UserService) {}
}

// user.service.ts
import { Injectable } from '@nestjs/common';
import { OrderService } from '../order/order.service';

@Injectable()
export class UserService {
  constructor(private orderService: OrderService) {}
}
After (fixed)
// order.service.ts
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { UserService } from '../user/user.service';

@Injectable()
export class OrderService {
  constructor(
    @Inject(forwardRef(() => UserService))
    private userService: UserService,
  ) {}
}

// user.service.ts
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { OrderService } from '../order/order.service';

@Injectable()
export class UserService {
  constructor(
    @Inject(forwardRef(() => OrderService))
    private orderService: OrderService,
  ) {}
}

// Also apply forwardRef in both modules:
// @Module({ imports: [forwardRef(() => UserModule)] })
// export class OrderModule {}

Testing the Fix

import { Test, TestingModule } from '@nestjs/testing';
import { OrderService } from './order.service';
import { UserService } from '../user/user.service';

describe('OrderService (circular dependency)', () => {
  let orderService: OrderService;
  let userService: UserService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        OrderService,
        { provide: UserService, useValue: { findOne: jest.fn().mockResolvedValue({ id: 1 }) } },
      ],
    }).compile();

    orderService = module.get<OrderService>(OrderService);
    userService = module.get<UserService>(UserService);
  });

  it('should resolve without circular dependency error', () => {
    expect(orderService).toBeDefined();
    expect(userService).toBeDefined();
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/nestjs-circular-dependency,git add src/order/order.service.ts src/user/user.service.ts src/order/order.module.ts src/user/user.module.ts,git commit -m "fix: resolve circular dependency with forwardRef",git push origin fix/nestjs-circular-dependency

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test -- --coverage
      - run: npm run build

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Initialize

import { initBugStack } from 'bugstack-sdk'

initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Identify the circular dependency chain from the error message.
  2. Apply forwardRef() on both sides of the circular reference.
  3. Consider refactoring to extract shared logic into a separate module.
  4. Run tests to verify all providers resolve correctly.
  5. Open a PR, merge after CI, and verify app bootstraps in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

forwardRef works but indicates a design smell. Long-term, consider extracting shared logic into a third service or using events to decouple the modules.

Use NestJS's built-in circular dependency detection during development. The framework logs a warning when it detects potential circles during module initialization.