NestJS

Lesson 07

Configuration module validation

Validate NestJS configuration at startup so missing environment variables fail before requests arrive.

Good Code

app.module.ts
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 {}

Bad Code

reviews.repository.ts
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!);
  }
}

Review Notes

What to review

Good Code

The good version validates required runtime configuration while the app boots. A bad deployment fails before serving traffic.

Bad Code

The bad version reads process.env inside a repository and asserts that the value exists. Missing configuration becomes a runtime request failure.

Takeaways

  • Configuration should be parsed once at startup and injected as typed values instead of read ad hoc from process.env.