패키지 설치하기
yarn add @nestjs/config
//혹은
npm i @nestjs/config
ENV 파일 작성하기
gitignore에 .env 추가하기
.env
.env 파일 작성
JWT_SECRET=jwtsecret
HASH_ROUNDS=10
PROTOCOL=http
HOST=localhost:3000
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=postgres
DB_PASSWORD=postgres
DB_DATABASE=postgres
환경변수 적용하기
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: '.env',
isGlobal: true,
}),
isGlobal을 하면 앱 내 어디서든 .env 파일을 사용할 수 있게 된다.
기존에 사용하던 로직들 제거
기존 파일이 제거 되었으므로 불필요한 로직을 제거한다.
@Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,
private readonly usersService: UsersService,
private readonly configService: ConfigService,
) {}
configService를 사용하므로 생성자에 추가해준다.
return this.jwtService.verify(token, {
secret: this.configService.get<string>('JWT_SECRET'),
});
configService.get<T>(키값) 형태로 .env의 파일에서 불러올 수 있다.
env-keys.const.ts 로 Key 매핑하기
// 서버 프로토콜 -> http / https
export const ENV_PROTOCOL_KEY = 'PROTOCOL';
// 서버 호스트 -> localhost:3000
export const ENV_HOST_KEY = 'HOST';
// JWT 토큰 시크릿 -> jwtsecret
export const ENV_JWT_SECRET_KEY = 'JWT_SECRET';
// JWT 토큰 해시 라운드 수 -> 10
export const ENV_HASH_ROUNDS_KEY = 'HASH_ROUNDS';
// 데이터베이스 호스트 -> localhost or 127.0.0.1
export const ENV_DB_HOST_KEY = 'DB_HOST';
// 데이터베이스 포트 -> 5432
export const ENV_DB_PORT_KEY = 'DB_PORT';
export const ENV_DB_USERNAME_KEY = 'DB_USERNAME';
export const ENV_DB_PASSWORD_KEY = 'DB_PASSWORD';
export const ENV_DB_DATABASE = 'DB_DATABASE';
secret: this.configService.get<string>(ENV_JWT_SECRET_KEY),
위와 같은 파일을 생성한다면 하드코딩을 하지 않고 손쉽게 불러올 수 있어진다.
process 객체를 이용해서 환경변수 불러오기
import { ClassSerializerInterceptor, Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { PostsModule } from './posts/posts.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { PostsModel } from './posts/entities/posts.entity';
import { UsersModule } from './users/users.module';
import { UsersModel } from './users/entities/users.entity';
import { AuthModule } from './auth/auth.module';
import { CommonModule } from './common/common.module';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { ConfigModule } from '@nestjs/config';
import { ENV_DB_DATABASE_KEY, ENV_DB_HOST_KEY, ENV_DB_PASSWORD_KEY, ENV_DB_PORT_KEY, ENV_DB_USERNAME_KEY } from './common/const/env-keys.const';
@Module({
imports: [
ConfigModule.forRoot({
envFilePath: '.env',
isGlobal: true,
}),
PostsModule,
TypeOrmModule.forRoot({
type: 'postgres',
host: process.env[ENV_DB_HOST_KEY],
port: parseInt(process.env[ENV_DB_PORT_KEY]!),
username: process.env[ENV_DB_USERNAME_KEY],
password: process.env[ENV_DB_PASSWORD_KEY],
database: process.env[ENV_DB_DATABASE_KEY],
entities: [PostsModel, UsersModel],
synchronize: true, //프로덕션 환경에선 false해야함
}),
UsersModule,
AuthModule,
CommonModule,
],
controllers: [AppController],
providers: [AppService, {
provide: APP_INTERCEPTOR,
useClass: ClassSerializerInterceptor,
}],
})
export class AppModule {}
app.module.ts에 TypeORM 설정 관련해서는 configService로 사용할 수 없으므로, process 객체를 위와 같이 사용하여야 한다.
'NestJS' 카테고리의 다른 글
[NestJS] 파일 업로드 (선 업로드 방식) (0) | 2025.03.07 |
---|---|
[NestJS] 파일 업로드 (클래식 방식) (0) | 2025.03.07 |
NestJS - Pagination 심화 (일반화하기) (0) | 2025.03.05 |
NetJS - Pagination 기본 (0) | 2025.03.02 |
NestJS - Class Transformer (0) | 2025.02.28 |