Nest.js

Nestjs ConfigModule 사용시 환경변수 boolean값을 가져올때 string으로 가져오는 문제

Dev갱이 2024. 6. 24. 14:09
728x90
let cookieOptions: CookieOptions = {
    maxAge: Number(this.configService.get<number>(ENV_COOKIE_MAX_AGE)),
    secure: this.configService.get(ENV_COOKIE_SECURE),
};

 

CookieOptions에서 secure 프로퍼티의 옵션에는 boolean 값만 올 수 있는데
typeof this.configService.get('COOKIE_SECURE')
typeof this.configService.get(ENV_COOKIE_SECURE)
> this.configService.get으로 .env 에 true나 false값을 가져오면 

***cookie_secure=*** string
***cookie_secure2=*** string
string 타입을 가져오는것을 알 수 있다. 그래서 런타임 환경에서 에러가 발생해버린다.
이를 해결 하기 위해서 환경변수 boolean 값을 가져올때에는 JSON.parse를 이용한다.

 

let cookieOptions: CookieOptions = {
    maxAge: Number(this.configService.get<number>(ENV_COOKIE_MAX_AGE)),
    secure: JSON.parse(this.configService.get(ENV_COOKIE_SECURE)!),
};

 

typeof JSON.parse(this.configService.get(ENV_COOKIE_SECURE)!)
***secure***= boolean
728x90