민프

[Nest.js][Error] [Nest] 53822 -ERROR [ExceptionsHandler] Error: secretOrPrivateKey must have a value 본문

Backend/[Nest.js]

[Nest.js][Error] [Nest] 53822 -ERROR [ExceptionsHandler] Error: secretOrPrivateKey must have a value

민프야 2025. 4. 7. 19:30

1. 에러 메세지

ERROR [ExceptionsHandler] Error: secretOrPrivateKey must have a value

 

2. 문제 정의

JWT 토큰을 서명(sign)하려고 할 때, 필요한 secretOrPrivateKey존재하지 않아서 발생하는 오류이다.

 

3. 원인 분석

  • env 파일에 JWT_SECRET 값이 정상적으로 불러오지 않았거나,
  • JwtModule.registerAsync(...)에서 secret 값을 설정하지 않았거나,
  • 설정했지만 해당 모듈에서 제대로 로딩되지 않아서 발생한 문제이다.
  • 결정적으로 사용하는 곳(auth)에서 JwtModule.registerAsync를 등록해줘야하는데 app.module.ts에다 설정을 해놓고 auth.module.ts에는 설정해주지 않아서 문제가 발생

 

4.  문제코드

app.module.ts <- 여기에다가 하면 안되고, 사용할 곳에서 써야함

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';

import { AppController } from './app.controller';
import { AppService } from './app.service';
import { AuthModule } from './auth/auth.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true, // 모든 모듈에서 process.env 사용 가능
      envFilePath: '.env', // ← 이 줄을 명시적으로 추가해줘
    }),
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        secret: configService.get<string>('JWT_SECRET'),
        signOptions: {
          expiresIn: configService.get<string>('JWT_EXPIRATION') || '1d',
        },
      }),
    }),
    AuthModule,
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
auth.module.ts <- 여기에다가 넣어야함

import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';

import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';

@Module({
  imports: [PassportModule],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService],
})
export class AuthModule {}

5. 해결 방법 

  • env 파일의 JWT_SECRET 값을 확인하고,
  • JwtModule.registerAsync(...)를 JWT가 필요한 모듈(AuthModule) 에서 등록하도록 한다.
  • ConfigModule.forRoot()를 AppModule에 추가하고 isGlobal: true로 설정하여, 모든 모듈에서 env 접근 가능하게 한다.
auth.module.ts

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';

import { AuthController } from './auth.controller';
import { AuthService } from './auth.service';
import { JwtStrategy } from './strategies/jwt.strategy';

@Module({
  imports: [
    PassportModule,
    JwtModule.registerAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (configService: ConfigService) => ({
        secret: configService.get<string>('JWT_SECRET'),
        signOptions: {
          expiresIn: configService.get<string>('JWT_EXPIRATION') || '1d',
        },
      }),
    }),
  ],
  controllers: [AuthController],
  providers: [AuthService, JwtStrategy],
  exports: [AuthService],
})
export class AuthModule {}
Comments