[nest.js] JwtModule에서 process.env 내용을 못 읽어 올 때
- 증상 : 다른 module 에서는 .env 내용을 잘 읽는데 jwt module 에서 못읽음
- 원인 : jwt module 이 환경설정이 메모리에 올라가기 전에 동작되기 때문
- 해결책 : 아래처럼 jwt module 이 사용되는 module 을 dynamic module 로 변경 한 뒤 app module 에서 사용
import { DynamicModule, Module } from "@nestjs/common";
import { JwtModule } from "@nestjs/jwt";
import { UserHttpModule } from "../user/user-http.module";
import { PassportModule } from "@nestjs/passport";
import { JwtStrategy } from "./jwt.strategy";
import { UserRepository } from "../user/user.repository";
import { AuthService } from "./auth.service";
import { AuthController } from "./auth.controller";
@Module( {} )
export class AuthModule
{
static forRoot() : DynamicModule
{
return {
imports : [
PassportModule.register( { defaultStrategy : "jwt" } ),
JwtModule.register( {
secret : process.env.JWT_SECRET_KEY,
signOptions : { expiresIn : Number( process.env.JWT_EXPIRES_IN ) }
} ),
UserHttpModule
],
controllers : [AuthController],
providers : [AuthService, JwtStrategy, UserRepository],
exports : [JwtStrategy, PassportModule],
module : AuthModule
};
}
}
imports :
[
AuthModule,
.
.
.
]
imports :
[
AuthModule.forRoot()
.
.
.
]
@UseGuards( AuthGuard( "jwt" ) )
참조 :
NestJs: Unable to read env variables in module files but able in service files?
I have an .env file at the root of my NestJs project with some env variables in it. The strange thing is that I am able to read the variables in service files but not in module files. So in a s...
