E

Environment Variables

Type-safe environment variable handling ensures configuration is properly validated.

Code

typescript
1// Type-safe environment configuration
2interface EnvConfig {
3 NODE_ENV: "development" | "production" | "test";
4 PORT: number;
5 DATABASE_URL: string;
6 API_KEY: string;
7 DEBUG: boolean;
8}
9
10// Environment variable parser
11function getEnvString(key: string, defaultValue?: string): string {
12 const value = process.env[key];
13 if (value === undefined) {
14 if (defaultValue !== undefined) return defaultValue;
15 throw new Error(`Missing required environment variable: ${key}`);
16 }
17 return value;
18}
19
20function getEnvNumber(key: string, defaultValue?: number): number {
21 const value = process.env[key];
22 if (value === undefined) {
23 if (defaultValue !== undefined) return defaultValue;
24 throw new Error(`Missing required environment variable: ${key}`);
25 }
26 const parsed = parseInt(value, 10);
27 if (isNaN(parsed)) {
28 throw new Error(`Environment variable ${key} must be a number`);
29 }
30 return parsed;
31}
32
33function getEnvBoolean(key: string, defaultValue?: boolean): boolean {
34 const value = process.env[key];
35 if (value === undefined) {
36 if (defaultValue !== undefined) return defaultValue;
37 throw new Error(`Missing required environment variable: ${key}`);
38 }
39 return value.toLowerCase() === "true" || value === "1";
40}
41
42// Load and validate configuration
43function loadConfig(): EnvConfig {
44 const nodeEnv = getEnvString("NODE_ENV", "development");
45
46 if (!["development", "production", "test"].includes(nodeEnv)) {
47 throw new Error(`Invalid NODE_ENV: ${nodeEnv}`);
48 }
49
50 return {
51 NODE_ENV: nodeEnv as EnvConfig["NODE_ENV"],
52 PORT: getEnvNumber("PORT", 3000),
53 DATABASE_URL: getEnvString("DATABASE_URL", "sqlite://local.db"),
54 API_KEY: getEnvString("API_KEY", "dev-key"),
55 DEBUG: getEnvBoolean("DEBUG", false),
56 };
57}
58
59// Usage
60const config = loadConfig();
61
62console.log("Configuration loaded:");
63console.log(` Environment: ${config.NODE_ENV}`);
64console.log(` Port: ${config.PORT}`);
65console.log(` Database: ${config.DATABASE_URL}`);
66console.log(` Debug mode: ${config.DEBUG}`);
67
68// Export for use in other modules
69export { config, EnvConfig };

Run this example locally

$ npx ts-node node/environment.ts