Real World Example

Reading Environment Variables

Every Node.js service (Uber, Netflix, any startup backend) reads configuration from environment variables. process.env.X is string | undefined. Writing process.env.DB_URL! everywhere hides missing config until a crash in production. A small helper fails fast with a clear message instead.

Example

process.env.PORT = "3000";
process.env.DB_URL = "postgres://localhost/shopease";

function requireEnv(name: string): string {
  const value = process.env[name];
  if (value === undefined || value === "") {
    throw new Error(`Missing environment variable ${name}`);
  }
  return value;
}

const port = Number(requireEnv("PORT"));
const dbUrl = requireEnv("DB_URL");
console.log("Port:", port, "| DB:", dbUrl);

try {
  requireEnv("RAZORPAY_KEY");
} catch (e) {
  console.log((e as Error).message);
}

Output

Port: 3000 | DB: postgres://localhost/shopease
Missing environment variable RAZORPAY_KEY