Server/NodeJS & NestJS

NestJS) JwtModule에서 .env 호출이 되지 않을 때

Juzdalua 2022. 4. 21. 12:14

config module에서 isGlobal:true로 설정해도 다음과 같은 에러가 나올 때도 있다.

return failure(new error('secretorprivatekey must have a value'));

 

JwtModule.register 대신 registerAsync를 사용하면 된다.

//auth.module.ts

import { Module } from '@nestjs/common';
import { JwtModule } from "@nestjs/jwt";
import { AuthService } from './auth.service';
import { JwtStrategy } from './jwt.strategy';
import {PassportModule} from "@nestjs/passport"
import { LocalStrategy } from './local.strategy';
import { ConfigService } from '@nestjs/config';

@Module({
    imports: [
        JwtModule.registerAsync({
            inject: [ConfigService],
            useFactory: (config: ConfigService) => ({
                secret: config.get<string>('JWT_SECRET_KEY'),
                signOptions: {expiresIn: '86400s'}
            })
        }),
        PassportModule
    ],
    controllers: [],
    providers: [
        AuthService,
        JwtStrategy,
        LocalStrategy
    ],
    exports: [
        AuthService,
    ]
})
export class AuthModule {}