0Pricing
NestJS Enterprise Backend APIs · 강의

Joi와 forRoot를 사용한 스키마 검증 환경 변수

ConfigModule.forRoot에서 Joi 스키마로 환경 변수를 검증해 부팅 시 즉시 실패하도록 구성합니다

Joi와 forRoot를 사용한 스키마 검증 환경 변수은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 NestJS Enterprise Backend APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Validate Env at Boot?

In enterprise NestJS services, configuration lives in environment variables. A missing DATABASE_URL or a typo like PORT=tree should never reach production traffic.

  • Fail fast: crash at startup, not on the first request three hours later.
  • Single source of truth: one schema documents every variable your app needs.
  • Type safety: coerce strings into numbers and booleans up front.

This lesson wires a Joi schema into ConfigModule.forRoot so the process refuses to boot when the environment is invalid.

The Problem Without Validation

Without validation, NestJS happily starts with bad config. The failure surfaces later, deep inside a service, with a confusing error.

Below, PORT arrives as a string and the math silently breaks. A real app would also dereference undefined secrets at runtime.

// A common silent bug: env vars are always strings
const PORT = process.env.PORT; // "3000" or undefined

// Expecting a number, but string concatenation happens instead
const nextPort = PORT + 1;
console.log('PORT:', PORT);
console.log('nextPort (wrong):', nextPort); // "30001", not 3001

// Missing secret is undefined, not an error
const secret = process.env.JWT_SECRET;
console.log('JWT_SECRET present?', secret !== undefined);

Installing the Pieces

You need two packages: the Nest config module and Joi itself.

  • @nestjs/config wraps dotenv and exposes ConfigService.
  • joi is the schema/validation library that forRoot calls internally.

Joi ships its own TypeScript types, so no separate @types package is required.

# Install the config module and Joi
npm install @nestjs/config joi

A First Joi Schema

A Joi schema is an object describing each variable's type, allowed values, and defaults. Validation runs against process.env.

This snippet is plain Node + Joi (no Nest), so you can see exactly what forRoot does under the hood.

const Joi = require('joi');

const schema = Joi.object({
  NODE_ENV: Joi.string()
    .valid('development', 'production', 'test')
    .default('development'),
  PORT: Joi.number().port().default(3000),
});

const { error, value } = schema.validate(
  { PORT: '8080' },
  { abortEarly: false, allowUnknown: true },
);

console.log('error:', error ? error.message : 'none');
console.log('PORT type:', typeof value.PORT, value.PORT); // number 8080
console.log('NODE_ENV default:', value.NODE_ENV);

Wiring the Schema into forRoot

Pass the schema as validationSchema to ConfigModule.forRoot. Use isGlobal: true so ConfigService is injectable everywhere without re-importing.

If the environment fails the schema, Nest throws during module initialization and the process exits non-zero.

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
      validationSchema: Joi.object({
        NODE_ENV: Joi.string()
          .valid('development', 'production', 'test')
          .default('development'),
        PORT: Joi.number().port().default(3000),
        DATABASE_URL: Joi.string().uri().required(),
        JWT_SECRET: Joi.string().min(32).required(),
      }),
    }),
  ],
})
export class AppModule {}

Required vs Default

The two most important Joi modifiers shape your fail-fast policy:

  • .required() — boot must fail if the variable is absent. Use for secrets and connection strings.
  • .default(value) — supply a safe fallback so the variable is optional.

Never give a secret like JWT_SECRET a default; that hides a misconfiguration and ships a known key.

import * as Joi from 'joi';

export const validationSchema = Joi.object({
  // Optional with a sensible fallback
  LOG_LEVEL: Joi.string()
    .valid('debug', 'info', 'warn', 'error')
    .default('info'),

  // Mandatory: no default, must be provided
  DATABASE_URL: Joi.string().uri().required(),
  JWT_SECRET: Joi.string().min(32).required(),
});

Type Coercion and Booleans

Every env var is a string. Joi coerces them so ConfigService.get returns real types.

  • Joi.number() turns "5432" into 5432.
  • Joi.boolean() understands "true"/"false" as real booleans.

This coercion is the value Joi adds beyond a plain presence check.

const Joi = require('joi');

const schema = Joi.object({
  DB_PORT: Joi.number().default(5432),
  CACHE_ENABLED: Joi.boolean().default(false),
});

const { value } = schema.validate(
  { DB_PORT: '6543', CACHE_ENABLED: 'true' },
  { allowUnknown: true },
);

console.log(typeof value.DB_PORT, value.DB_PORT);       // number 6543
console.log(typeof value.CACHE_ENABLED, value.CACHE_ENABLED); // boolean true

validationOptions: Report Every Error

By default Joi stops at the first error (abortEarly: true). In CI and local setup you want the full list, so pass validationOptions.

  • abortEarly: false — collect and print all missing/invalid vars at once.
  • allowUnknown: true — tolerate extra OS vars like PATH (the default).
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';

ConfigModule.forRoot({
  isGlobal: true,
  validationSchema: Joi.object({
    DATABASE_URL: Joi.string().uri().required(),
    JWT_SECRET: Joi.string().min(32).required(),
    REDIS_URL: Joi.string().uri().required(),
  }),
  validationOptions: {
    abortEarly: false, // show ALL problems, not just the first
    allowUnknown: true,
  },
});

Conditional Rules with Joi.when

Enterprise configs differ per environment. Joi expresses this with .when(): tighten rules only in production.

Here, TLS must be enabled and a sentry DSN must be present when NODE_ENV is production, but stay optional otherwise.

import * as Joi from 'joi';

export const validationSchema = Joi.object({
  NODE_ENV: Joi.string()
    .valid('development', 'production', 'test')
    .default('development'),

  DB_SSL: Joi.boolean().when('NODE_ENV', {
    is: 'production',
    then: Joi.valid(true).required(),
    otherwise: Joi.boolean().default(false),
  }),

  SENTRY_DSN: Joi.string().uri().when('NODE_ENV', {
    is: 'production',
    then: Joi.required(),
    otherwise: Joi.optional(),
  }),
});

Reading Validated Config in a Service

Once validation passes, inject ConfigService and read typed values. Use the generic form get<number> for the right return type.

Because the schema guarantees presence, you can safely assert non-null for required keys.

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class DatabaseConfig {
  constructor(private readonly config: ConfigService) {}

  get url(): string {
    // Required in the schema, so it is guaranteed present
    return this.config.get<string>('DATABASE_URL')!;
  }

  get port(): number {
    // Already coerced to a number by Joi
    return this.config.get<number>('DB_PORT', 5432);
  }
}

What a Boot Failure Looks Like

When validation fails, Nest throws before listening on the port. The message lists each offending variable, which is gold for debugging deploys.

A typical crash with abortEarly: false reports multiple problems together.

// Simulated message thrown by @nestjs/config on bad env
// Error: Config validation error:
//   "DATABASE_URL" is required.
//   "JWT_SECRET" length must be at least 32 characters long.
//   "PORT" must be a valid port.
//
// Process exits with a non-zero code; no requests are served.

console.log('Boot aborted: fix the env vars listed above.');

Quick Check

Test your understanding of fail-fast env validation.

Recap

You made configuration fail fast with Joi:

  • Pass a Joi.object schema as validationSchema to ConfigModule.forRoot, with isGlobal: true.
  • Mark secrets and connection strings .required(); give safe values .default(); never default a secret.
  • Joi coerces strings into numbers and booleans, so ConfigService.get returns real types.
  • Set validationOptions.abortEarly: false to surface every problem at once.
  • Use .when() to enforce stricter rules in production.

The payoff: a broken environment crashes at startup with a clear list, never silently mid-request.

자주 묻는 질문

“Joi와 forRoot를 사용한 스키마 검증 환경 변수” 강의는 무료인가요?

네 — “Joi와 forRoot를 사용한 스키마 검증 환경 변수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“Joi와 forRoot를 사용한 스키마 검증 환경 변수”에서 뭘 배우나요?

ConfigModule.forRoot에서 Joi 스키마로 환경 변수를 검증해 부팅 시 즉시 실패하도록 구성합니다 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“Joi와 forRoot를 사용한 스키마 검증 환경 변수” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Joi와 forRoot를 사용한 스키마 검증 환경 변수
  2. registerAs를 사용한 네임스페이스 구성
  3. HashiCorp Vault와 AWS SSM에서 비밀 값 불러오기
  4. 환경별 구성과 안전한 기본값
← NestJS Enterprise Backend APIs(으)로 돌아가기