Typing Environment Variables
Give process.env a precise, validated type.
The Problem with process.env
In Node, process.env is typed as Record<string, string | undefined>. Every variable might be missing, and everything is a string, so raw access is unsafe and untyped.
Declaring a Typed Env Interface
Start by describing the configuration your app actually needs as a precise interface, with correct types and required versus optional fields.
interface Env {
PORT: number;
NODE_ENV: "development" | "production";
DATABASE_URL: string;
DEBUG?: boolean; // optional
}All lessons in this course
- Typing Environment Variables
- Schema-Validated Config
- Config Layering and Defaults
- Secrets and Type Safety