Good Code
The good version turns environment variables into a typed config object and fails during startup if required values are missing.
Lesson 04
Read and validate environment configuration once at startup.
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 };
}export function connectDatabase() {
return connect({
url: process.env.DATABASE_URL || "postgres://localhost/dev",
poolSize: Number(process.env.POOL_SIZE || "not-a-number"),
});
}The good version turns environment variables into a typed config object and fails during startup if required values are missing.
The bad version reads process.env deep inside infrastructure code, silently falls back to a local database, and accepts invalid numeric config.