การกำหนดค่าแยกตามสภาพแวดล้อมและค่าเริ่มต้นที่ปลอดภัย
ซ้อนทับการกำหนดค่าสำหรับ development, staging และ production พร้อมคงค่าเริ่มต้นสำรองที่เหมาะสม
การกำหนดค่าแยกตามสภาพแวดล้อมและค่าเริ่มต้นที่ปลอดภัย เป็นบทเรียน NestJS Enterprise Backend APIs ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน NestJS Enterprise Backend APIs และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Why Per-Environment Config Matters
An enterprise NestJS API runs in several places at once: a developer's laptop, a staging cluster, and production. Each needs different values: database URLs, log levels, feature flags, third-party keys.
- Development favors convenience: verbose logs, local DB, relaxed timeouts.
- Staging mirrors production but with test data and safer credentials.
- Production favors safety and performance: strict logging, real secrets, hardened defaults.
The goal of this lesson is to layer these environments so a single codebase behaves correctly everywhere, while keeping sensible fallback defaults when a value is missing.
The NODE_ENV Signal
The conventional way to tell environments apart is the NODE_ENV variable. Nest itself, and most tooling, read it to decide behavior.
A robust app should never assume NODE_ENV is set. Treat a missing value as development so a fresh checkout still runs, but never silently treat an unknown value as production.
type AppEnv = 'development' | 'staging' | 'production';
function resolveEnv(raw: string | undefined): AppEnv {
const value = (raw ?? 'development').toLowerCase();
if (value === 'production' || value === 'prod') return 'production';
if (value === 'staging' || value === 'stage') return 'staging';
return 'development';
}
console.log(resolveEnv(undefined)); // development
console.log(resolveEnv('PRODUCTION')); // production
console.log(resolveEnv('stage')); // stagingLoading .env Files in Order
NestJS's ConfigModule can load multiple .env files. The order matters: the first file to define a key wins, so list the most specific file first.
A common layout: a per-environment file (e.g. .env.production) overrides a shared base .env. This is how you layer overrides on top of safe defaults.
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
// First match wins: env-specific overrides the shared base.
envFilePath: [`.env.${process.env.NODE_ENV ?? 'development'}`, '.env'],
cache: true,
}),
],
})
export class AppModule {}Safe Defaults with a Config Factory
Hardcoding fallbacks all over the codebase is fragile. Instead, centralize them in a configuration factory that reads process.env once and applies defaults in a single place.
Notice how each value has a fallback: the app still boots even if an optional variable is missing, but the default is intentional rather than accidental.
export default () => ({
port: parseInt(process.env.PORT ?? '3000', 10),
logLevel: process.env.LOG_LEVEL ?? 'info',
database: {
host: process.env.DB_HOST ?? 'localhost',
port: parseInt(process.env.DB_PORT ?? '5432', 10),
poolSize: parseInt(process.env.DB_POOL_SIZE ?? '10', 10),
},
features: {
rateLimiting: process.env.FEATURE_RATE_LIMIT === 'true',
},
});Defaults That Differ by Environment
Some defaults should themselves depend on the environment. For example, you want chatty debug logs locally but quiet warn logs in production, even if LOG_LEVEL is never explicitly set.
Compute environment-aware defaults before applying the env-var override, so an explicit value always wins but the fallback is still sensible.
type Env = 'development' | 'staging' | 'production';
function defaultsFor(env: Env) {
const base = { logLevel: 'info', requestTimeoutMs: 30000, debugRoutes: false };
if (env === 'development') return { ...base, logLevel: 'debug', debugRoutes: true };
if (env === 'production') return { ...base, logLevel: 'warn', requestTimeoutMs: 10000 };
return base; // staging keeps the base
}
const env: Env = 'production';
const cfg = { ...defaultsFor(env), logLevel: process.env.LOG_LEVEL ?? defaultsFor(env).logLevel };
console.log(cfg); // { logLevel: 'warn', requestTimeoutMs: 10000, debugRoutes: false }Validating Config at Startup
Safe defaults must not hide missing required secrets. A production API should refuse to start if, say, JWT_SECRET is absent rather than fall back to a guessable default.
The ConfigModule supports a validate function (or a Joi schema) that runs at boot and throws on invalid config. Fail fast and loud.
import { plainToInstance } from 'class-transformer';
import { IsEnum, IsInt, IsString, MinLength, validateSync } from 'class-validator';
enum Environment { Development = 'development', Staging = 'staging', Production = 'production' }
class EnvVars {
@IsEnum(Environment) NODE_ENV: Environment;
@IsInt() PORT: number;
@IsString() @MinLength(16) JWT_SECRET: string;
}
export function validate(config: Record<string, unknown>) {
const parsed = plainToInstance(EnvVars, config, { enableImplicitConversion: true });
const errors = validateSync(parsed, { skipMissingProperties: false });
if (errors.length) throw new Error(errors.toString());
return parsed;
}Never Default a Secret
There is a sharp line between an optional value (safe to default) and a secret (never safe to default).
- Optional:
LOG_LEVEL,PORT, pool sizes, feature flags. Defaulting keeps dev frictionless. - Secret/required:
JWT_SECRET,DB_PASSWORD, payment keys. A default here is a security hole.
A helper that throws for required keys makes the intent explicit and prevents a missing secret from being silently replaced.
function required(name: string, value: string | undefined): string {
if (value === undefined || value.trim() === '') {
throw new Error(`Missing required config: ${name}`);
}
return value;
}
function optional(value: string | undefined, fallback: string): string {
return value ?? fallback;
}
// Demo with fake values:
const port = optional(undefined, '3000');
console.log('port:', port); // 3000
try {
required('JWT_SECRET', undefined);
} catch (e) {
console.log((e as Error).message); // Missing required config: JWT_SECRET
}Typed Access with ConfigService
Inside services, read config through the injected ConfigService rather than touching process.env directly. This gives you a single source of truth, typed access, and the ability to supply an inline default as the second argument.
The infer: true option returns the precise type from your config factory, so the compiler catches typos in config paths.
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class DatabaseConfig {
constructor(private readonly config: ConfigService) {}
get poolSize(): number {
// Inline default acts as a last-resort fallback.
return this.config.get<number>('database.poolSize', 10);
}
get host(): string {
return this.config.get<string>('database.host', 'localhost');
}
}Namespaced Config with registerAs
As config grows, group related keys into namespaces using registerAs. Each namespace is its own factory with its own defaults, and can be injected as a strongly typed token.
For example, a database namespace owns host, port, and ssl, each with its own ?? fallback, while a cache namespace owns the Redis URL and TTL. This keeps database, cache, and auth settings cohesive, and lets each team own its slice without one giant object. You then inject the slice you need (for example with @Inject(databaseConfig.KEY)) instead of reaching into a global config object.
Production Overrides via Real Env Vars
In production you usually do not ship a .env.production file with real secrets. Instead the platform (Kubernetes secrets, AWS Parameter Store, Docker env) injects variables directly into the process.
Because process.env values always take precedence over a baked-in .env file in the load order, your safe defaults stay as the floor and the platform's injected values become the override. This is the layering payoff: defaults at the bottom, env-specific files in the middle, real injected env vars on top.
Putting the Layers Together
The full precedence chain, from lowest to highest priority:
- 1. Code defaults in the config factory (e.g.
?? 'localhost'). - 2. Shared base
.env(committed defaults, no secrets). - 3. Env-specific file
.env.staging/.env.production. - 4. Process env vars injected by the platform (highest).
Validation runs once at boot across the merged result, so a wrong type or a missing required secret stops the app immediately, in every environment.
function buildConfig(env: NodeJS.ProcessEnv) {
const defaults = { dbHost: 'localhost', logLevel: 'info' };
const merged = {
dbHost: env.DB_HOST ?? defaults.dbHost,
logLevel: env.LOG_LEVEL ?? defaults.logLevel,
};
if (env.NODE_ENV === 'production' && !env.DB_PASSWORD) {
throw new Error('DB_PASSWORD is required in production');
}
return merged;
}
console.log(buildConfig({ DB_HOST: 'db.internal' } as NodeJS.ProcessEnv));
// { dbHost: 'db.internal', logLevel: 'info' }Quick Check: Defaults vs Secrets
You are wiring config for a NestJS API. LOG_LEVEL is optional and JWT_SECRET is required. Which approach correctly layers safe defaults while staying secure in production?
Recap: Layered Config and Safe Defaults
You now know how to make one NestJS codebase behave correctly across development, staging, and production:
- Resolve the environment from
NODE_ENV, defaulting to development, never silently to production. - Load
.envfiles in most-specific-first order so env files override the shared base. - Centralize safe defaults in a config factory, and make some defaults environment-aware.
- Never default a secret: validate required keys at startup and fail fast.
- Access config through a typed
ConfigServiceand group keys withregisterAs. - Remember the precedence: code defaults < base .env < env-specific file < injected process env.
The result is layered overrides on a foundation of sensible, intentional defaults.
เรียนรู้ TypeScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 20
- บทเรียน
- 76
คำถามที่พบบ่อย
บทเรียน “การกำหนดค่าแยกตามสภาพแวดล้อมและค่าเริ่มต้นที่ปลอดภัย” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การกำหนดค่าแยกตามสภาพแวดล้อมและค่าเริ่มต้นที่ปลอดภัย” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส NestJS Enterprise Backend APIs ให้อัปเกรดเป็น CoddyKit PRO คอร์ส NestJS Enterprise Backend APIs มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การกำหนดค่าแยกตามสภาพแวดล้อมและค่าเริ่มต้นที่ปลอดภัย”
ซ้อนทับการกำหนดค่าสำหรับ development, staging และ production พร้อมคงค่าเริ่มต้นสำรองที่เหมาะสม คุณปฏิบัติ NestJS Enterprise Backend APIs ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน NestJS Enterprise Backend APIs หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน NestJS Enterprise Backend APIs บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน
บทเรียน “การกำหนดค่าแยกตามสภาพแวดล้อมและค่าเริ่มต้นที่ปลอดภัย” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน NestJS Enterprise Backend APIs นี้ได้ไหม
ได้ บทเรียน NestJS Enterprise Backend APIs ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- ตัวแปรสภาพแวดล้อมที่ตรวจสอบสคีมาด้วย Joi และ forRoot
- การกำหนดค่าแบบมีเนมสเปซด้วย registerAs
- การโหลดความลับจาก HashiCorp Vault และ AWS SSM
- การกำหนดค่าแยกตามสภาพแวดล้อมและค่าเริ่มต้นที่ปลอดภัย