DEV Community

Vincent Jang
Vincent Jang

Posted on

1 1

JWT secret with .env file but error occur in NESTJS

Error Occured

최근 사이드 프로젝트를 시작하면서 NestJS 를 다루게 되었다.
JWT 모듈을 .env 파일을 이용하여 다루던 도중 다음과 같은 에러를 만나게 되었다.

Image description

Problem Solving Method

아무리 코드를 뒤져봐도 어떤 문제가 보이지 않아 구글링을 시작했을 때
다음과 같은 해결책을 찾을 수 있었다.

Before Code

기존의 내 코드는 다음과 같았다.

// in auth.module.ts
JwtModule.register({
      secret : process.env.JWT_SECRET,
      signOptions: {
        expiresIn: 60 * 60
      }      
    }),
Enter fullscreen mode Exit fullscreen mode

이 코드는 .env 에 있는 JWT Secret 을 불러와 사용하는 코드였는데,
env variable 를 불러오는 것과 애플리케이션이 실행되는 것은 비동기 처리라는 것을 알게되었다.

따라서 JwtModule 에서는 다음과 같은 method 를 지원했다.
JwtModule.registerAsync({})

해당 메소드는 환경변수를 읽을 때 까지 모듈 설정을 유보할 수 있도록 도와준다.

따라서 다음과 같이 작성하여 해결하였다.

After Code

JwtModule.registerAsync({
      // .env 에 등록되어 있는 것을 가져오는것이 비동기 작업이므로, 초기화 시에 env 요소를 못불러온 상태일 수 있음.
      // 따라서 registerAsync, ConfigService 를 사용해 동기적으로 작업함
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        secret: config.get<string>('JWT_SECRET'),
        signOptions : {
          expiresIn: 60 * 60
        }
      })  
    }),
Enter fullscreen mode Exit fullscreen mode

나와 같은 뉴비 개발자들에게 도움이 되었길 바란다.

  • 이 글의 구글링 결과 원문을 찾지 못하였습니다. 찾는대로 레퍼런스를 기록합니다.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay