NestJS "A circular dependency has been detected" in CI
Two providers or modules depend on each other, so when Nest constructs the first, the second is still undefined. Nest warns about the cycle and injection resolves to undefined.
What this error means
Startup logs "A circular dependency has been detected inside X. Please, make sure that each side of a bidirectional relationship is decorated with forwardRef()." Injected dependencies then arrive as undefined.
[Nest] WARN A circular dependency has been detected inside "CatsService". Please,
make sure that each side of a bidirectional relationship is decorated with "forwardRef()".
Nest cannot create the module instance.Common causes
Two providers inject each other
CatsService needs UsersService and UsersService needs CatsService; neither can be constructed first without the other existing.
Two modules import each other
Module A imports Module B and Module B imports Module A, creating a module-level cycle Nest cannot order.
How to fix it
Wrap each side in forwardRef
- Identify the two sides of the cycle from the warning.
- Wrap the injected reference with
forwardRef(() => Other)on both sides. - Do the same for
importswhen the cycle is between modules.
@Injectable()
export class CatsService {
constructor(
@Inject(forwardRef(() => UsersService))
private users: UsersService,
) {}
}Break the cycle by extracting shared code
Move the shared logic into a third provider both sides depend on, so the direct cycle disappears.
How to prevent it
- Prefer a unidirectional dependency graph; extract shared logic to a common provider.
- Reserve forwardRef for genuine bidirectional needs.
- Compile the module graph in a CI test so cycles surface immediately.