Node.js

Lesson 04

Environment variables and configuration

Read and validate environment configuration once at startup.

Good Code

src/config.ts
type AppConfig = {
  port: number;
  databaseUrl: string;
};

export function readConfig(env: NodeJS.ProcessEnv): AppConfig {
  const databaseUrl = env.DATABASE_URL;
  const port = Number(env.PORT ?? "3000");

  if (!databaseUrl) {
    throw new Error("DATABASE_URL is required.");
  }

  if (!Number.isInteger(port) || port < 1) {
    throw new Error("PORT must be a positive integer.");
  }

  return { databaseUrl, port };
}

Bad Code

src/db.ts
export function connectDatabase() {
  return connect({
    url: process.env.DATABASE_URL || "postgres://localhost/dev",
    poolSize: Number(process.env.POOL_SIZE || "not-a-number"),
  });
}

Review Notes

What to review

Good Code

The good version turns environment variables into a typed config object and fails during startup if required values are missing.

Bad Code

The bad version reads process.env deep inside infrastructure code, silently falls back to a local database, and accepts invalid numeric config.

Takeaways

  • Config should fail fast with clear messages instead of scattering process.env reads.