Post

NestJs 순환 종속성

순환 종속성 오류 (circular dependency error)

프로젝트에서 JWT 인증 Gaurd 구현을 위해서 UserModule에선 AuthModule를 import하고 Auth에선 UserMoudle을 import 하고있었다.

그런데 module에서 분명히 import되어 있는데 inject이 비어있다는 거다? 그래서 자세히 살펴보니

아래와 같은 설명이 되어있더라.

A circular dependency between modules. Use forwardRef() to avoid it. Read more: https://docs.nestjs.com/fundamentals/circular-dependency

이게 무슨 뜻인가 하면 두 클래스가 서로 종속되는 관계일 때 순환 종속성 이 발생할 수 있다는 거다.
Nest는 순방향 참조를 기본으로 하기 때문에 AuthModule <-> UserModule 이런 상태인 경우엔 Inject 혹은 import 할 때 따로 처리를 해줘야 한다는 말이다.

Solution

아래와 같이 서로 종속되는 module 파일에서 import 시에 forwardRef()함수로 참조시켜주면 해결된다.

1
2
3
4
@Module({
  imports: [forwardRef(() => UserModule)],
})
export class AuthenticationModule {}
This post is licensed under CC BY 4.0 by the author.