Environment Variables
In this page:
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
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
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
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
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
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: