Loading...
본문 바로가기
👥
총 방문자
📖
0개 이상
총 포스팅
🧑
오늘 방문자 수
📅
0일째
블로그 운영

여러분의 방문을 환영해요! 🎉

다양한 개발 지식을 쉽고 재미있게 알려드리는 블로그가 될게요. 함께 성장해요! 😊

코딩 정보/NestJs

[NestJs] 환경변수 세팅을 해보자

by 꽁이꽁설꽁돌 2025. 2. 3.
728x90
반응형
     

목차

     

    우리는 깃같은 공유 레포에 올리기 때문에 민감한 정보가 올라가는 것을 피하고 싶다.

    따라서 다음과 같이 설정해 주면 된다.

     

    env 사전 설정

     

    1. config 설치

    > yarn add @nestjs/config

     

     

    2. .env 파일 만들기

    JWT_SECRET = kkongdol
    HASH_ROUNDS = 10
    PROTOCOL = http
    HOST = localhost:3000
    
    DB_HOST = localhost
    DB_PORT=5432
    DB_USERNAME=postgres
    DB_PASSWORD=postgres
    DB_DATABASE=postgres

     

     

    3. .gitinore에 올리기

    .env

     

     

     

    4. app.module.ts에서 ConfigModule 불러오기

     ConfigModule.forRoot({
          envFilePath: '.env',
          isGlobal: true,
        }),

     

     

     

    5. 자동 불러오기 및 오타를 위해서 미리 세팅할 변수들

     

    env-keys.const.ts

    // 서버 프로토콜 -> http / https
    export const ENV_PROTOCOL_KEY = 'PROTOCOL';
    
    //서버 호스트 -> localhost:3000
    export const ENV_HOST_KEY = 'HOST';
    
    //JWT 토큰 시크릿 -> kkongdol
    export const ENV_JWT_SECRET_KEY = 'JWT_SECRET';
    
    export const ENV_HASH_ROUNDS_KEY = 'HASH_ROUNDS';
    
    export const ENV_DB_HOST_KEY = 'DB_HOST';
    
    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_KEY = 'DB_DATABASE';

     

     

     

     

    두가지 사용방법

    1. configservice 이용하기

      constructor(
        @InjectRepository(PostsModel)
        private readonly postsRepository: Repository<PostsModel>,
        private readonly commonService: CommonService,
        private readonly configService: ConfigService,
      ) {}
      
      
      
        const protocol = this.configService.get<string>(ENV_PROTOCOL_KEY);
        const host = this.configService.get<string>(ENV_HOST_KEY);
        const nextUrl = lastItem && new URL(`${protocol}://${host}/posts?`);

     

     

    2.process.env 이용하기

    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: [
        PostsModule,
        ConfigModule.forRoot({
          envFilePath: '.env',
          isGlobal: true,
        }),
        //type orm과 nestjs 연결
        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,
        }),
        UsersModule,
        AuthModule,
        CommonModule,
      ],
      controllers: [AppController],
      providers: [
        AppService,
        {
          provide: APP_INTERCEPTOR,
          useClass: ClassSerializerInterceptor,
        },
      ],
    })
    export class AppModule {}

     

     

    강의출처

     

    [코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core 강의 | 코드팩토리 -

    코드팩토리 | 자바스크립트, 타입스크립트 다음은 백엔드 개발! NestJS를 이용한 REST API 백엔드 개발, Socket IO 개발 및 배포를 할 수 있게 됩니다., 백엔드가 처음이어도 누구나 OK! 트렌디한 NestJS로

    www.inflearn.com

     

    반응형