![[NestJS] JWT secretOrPrivateKey must have a value](https://img1.daumcdn.net/thumb/R750x0/?scode=mtistory2&fname=https%3A%2F%2Fblog.kakaocdn.net%2Fdn%2FK0B2K%2FbtszAkxrA6W%2FVRM9v5Y3fF7i7K9GWK7Lp0%2Fimg.png)
에러 메세지
원인
.env에 작성해 둔 JWT_SECRET이라는 이름의 환경변수를 읽는 과정에서 발생한 에러로 JWT 토큰 발행 시 반드시 secret key가 있어야 하는데 읽지를 못한 것으로 보인다.
공식 문서의 JWT 가이드 대로 따라하며 토큰 발급 시 발생했으며, 모듈에서 설정한 secret을 JwtModule에 등록하지 못했다.
환경변수를 읽어오기 전에 secret가 먼저 register되는 것 같아 보였다.
@Module({
imports: [
UserModule,
JwtModule.register({
global: true,
secret: process.env.JWTSecret,
signOptions: { expiresIn: '60s' },
}),
TypeOrmModule.forFeature([
])
],
providers: [AuthService],
controllers: [AuthController],
exports: [AuthService],
})
export class AuthModule {}
Documentation | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea
docs.nestjs.com
해결
JwtModule의 registerAsync 함수를 사용했음.
이름에서도 유추할 수 있듯이 등록이 되는 것을 아래 프로퍼티들을 읽어올 때 까지 기다렸다 완료시키는 함수이다.
ConfigService를 주입하여 config에 있는 환경변수를 읽어오는 작업을 수행하게 할 수 있다.
@Module({
imports: [
UserModule,
JwtModule.registerAsync({
inject: [ConfigService],
global: true,
useFactory: (config: ConfigService) => ({
secret: config.get<string>('JWT_SECRET'),
signOptions: { expiresIn: config.get<string>('expiresIn') },
})
}),
TypeOrmModule.forFeature([
])
],
providers: [AuthService],
controllers: [AuthController],
exports: [AuthService],
})
export class AuthModule {}
참조
NestJs - ConfigModule.forRoot isGlobal not working
I am trying to load the "process.env.AUTH_SECRET" in AuthModule, but it is giving me the undefined error "Error: secretOrPrivateKey must have a value". I did setup the "isG...
stackoverflow.com
NestJS - can't resolve ConfigService
I am using NestJS jwt passport to auth user. I follow the doc, here is my app module: import { Module } from '@nestjs/common'; import { UserModule } from './user/user.module'; import { TypeOrmMod...
stackoverflow.com
2023.04 ~ 백엔드 개발자의 기록
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!