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
Here's what each line means:
- at Injector.resolveComponentInstance (node_modules/@nestjs/core/injector/injector.js:204:19): The NestJS injector detected that resolving this provider leads back to itself through a chain of dependencies.
- at Injector.resolveConstructorParams (node_modules/@nestjs/core/injector/injector.js:143:27): While resolving constructor parameters, the injector found that a dependency requires the same provider being constructed.
- at InstanceLoader.createInstancesOfProviders (node_modules/@nestjs/core/injector/instance-loader.js:44:9): The instance loader creates all providers during bootstrap, where circular chains are detected.
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.
// 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) {}
}
// 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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Identify the circular dependency chain from the error message.
- Apply forwardRef() on both sides of the circular reference.
- Consider refactoring to extract shared logic into a separate module.
- Run tests to verify all providers resolve correctly.
- 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.