[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
		};
	}
}
AuthModule
imports :
[
	AuthModule,
    .
    .
    .
]
app module 의 이 부분을
imports :
[
	AuthModule.forRoot()
    .
    .
    .
]
이렇게 변경
@UseGuards( AuthGuard( "jwt" ) )
그리고 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...

Subscribe to X세대 신입사원

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe
774-86-01972 cinnabar.3d@gmail.com