본문 바로가기
backend/NestJS

[NestJS] EC2 배포 시 secretOrPrivateKey must have a value 해결

by BK0625 2024. 4. 23.
반응형

현재 개발 중이던 프로젝트를 ec2에 올려 테스트 배포를 시도 했다.

 

ec2 인스턴스를 열고 nodejs를 설치하고 깃헙에서 코드를 받아 배포를 했는데...

 

 

 

이런 에러가 떴다. 쉽게 말하면 .env에 있는 jwtConstant라는 환경 변수를 읽는 과정에서 발생한 에러로 JWT 토큰 발행 시 있어야 하는 secret key를 읽지 못해 발생하는 에러이다.

 

 

로컬에서는 잘 되었는데... 아마 환경변수를 읽어 오기 전 시크릿 키가 먼저 register 되는 것 같았다.

 

//기존 코드
@Module({
  imports:[
    JwtModule.register({
      global: true,
      secret: jwtConstants.secret,
      signOptions: { expiresIn: '1d' },
    }),
  ],
  controllers:[UserController],
  providers: [UserService,PrismaService]
})
export class UserModule {}

 

 

구글링 해보니 jwtModule에 registerAsync 함수가 있었다. 말 그대로 등록이 되는 것을 값들을 다 읽어올 때까지 기다렸다가 완료시키는 함수이다.

 

ConfigService를 주입하여 config의 환경 변수를 읽어오는 작업을 수행하게 했다.

 

@Module({
  imports:[
    JwtModule.registerAsync({
      inject:[ConfigService],
      global: true,
      useFactory:(config:ConfigService) => ({
        secret: config.get<string>('jwtConstant'),
        signOptions: { expiresIn: '1d' },
      }),
     
    }),
  ],
  controllers:[UserController],
  providers: [UserService,PrismaService]
})
export class UserModule {}

 

 

문제가 해결 되었다:)

 

 

 

공부하면서 정리한 내용입니다. 모든 지적 감사히 받겠습니다:)

반응형