← Back to TypeScript Course | Chapter 13: TypeScript with Node.js | Lesson 6 of 6

Environment Variables

Environment variables allow configuration such as ports, API keys, and database URLs to be supplied outside the source code. In Node.js, they are available through process.env and are represented as possibly undefined strings.

Reading Environment Variables

Reading environment variables through process.env in Node returns values typed as string | undefined, correctly reflecting that an expected variable might simply not be set when your program starts.

Example: Reading Environment Variables

typescript
const apiKey: string | undefined = process.env.API_KEY;
console.log(apiKey);

Environment Variables and Numbers

Environment variables are always strings, so anything meant to be numeric — like a port number — needs an explicit conversion with Number() or parseInt, since process.env.PORT alone is typed as a string, never a number.

Example: Environment Variables and Numbers

typescript
const port: number = Number(process.env.PORT) || 3000;
console.log(port);

Validating Required Variables

Validating required variables means checking each one exists (and throwing early if it doesn't) right at startup, converting the string | undefined type into a guaranteed string for the rest of the program to safely use.

Example: Validating Required Variables

typescript
function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing env var: ${name}`);
  return value;
}
console.log(typeof requireEnv);

Typed Configuration Objects

A typed configuration object built once at startup — reading and validating every environment variable up front — means the rest of your codebase can import a fully-typed config object instead of repeatedly checking process.env everywhere.

Example: Typed Configuration Objects

typescript
interface AppConfig {
  port: number;
  apiKey: string;
}
const config: AppConfig = {
  port: Number(process.env.PORT) || 3000,
  apiKey: process.env.API_KEY || "dev-key",
};
console.log(config);

Environment Variables in a Node Server

In a Node server, validating environment variables before calling app.listen() ensures a missing critical variable (like a database URL) fails fast at boot instead of causing a confusing runtime error deep inside a request handler later.

Example: Environment Variables in a Node Server

typescript
function requireEnv(name: string): string {
  const value = process.env[name];
  if (!value) throw new Error(`Missing env var: ${name}`);
  return value;
}
// const dbUrl = requireEnv("DATABASE_URL"); // fails fast at boot
console.log("Validate env vars before app.listen() to fail fast");
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.