Good Code
The good version validates required runtime configuration while the app boots. A bad deployment fails before serving traffic.
Lesson 07
Validate NestJS configuration at startup so missing environment variables fail before requests arrive.
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
validate(config) {
// Startup fails if required runtime config is absent.
if (!config.DATABASE_URL) {
throw new Error("DATABASE_URL is required");
}
return config;
},
}),
],
})
export class AppModule {}import { Injectable } from "@nestjs/common";
@Injectable()
export class ReviewsRepository {
connect() {
// A missing env var appears only when this method is called.
return connectToDatabase(process.env.DATABASE_URL!);
}
}The good version validates required runtime configuration while the app boots. A bad deployment fails before serving traffic.
The bad version reads process.env inside a repository and asserts that the value exists. Missing configuration becomes a runtime request failure.