typescriptbeginner
Environment Secrets Loader
Loads and validates required environment variables at startup and throws meaningful errors for missing ones.
typescriptPress ⌘/Ctrl + Shift + C to copy
interface EnvConfig {
DATABASE_URL: string;
JWT_SECRET: string;
PORT: number;
NODE_ENV: 'development' | 'production' | 'test';
}
function loadEnv(): EnvConfig {
const required = ['DATABASE_URL', 'JWT_SECRET'] as const;
const missing = required.filter((key) => !process.env[key]);
if (missing.length > 0) {
throw new Error(
`Missing required environment variables: ${missing.join(', ')}`
);
}
return {
DATABASE_URL: process.env.DATABASE_URL!,
JWT_SECRET: process.env.JWT_SECRET!,
PORT: parseInt(process.env.PORT || '3000', 10),
NODE_ENV: (process.env.NODE_ENV as EnvConfig['NODE_ENV']) || 'development',
};
}
export const env = loadEnv();Use Cases
- Application bootstrap
- 12-factor app configuration
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Environment Variable Validator
Validates required environment variables at startup and returns a typed config object or throws with missing keys.
Best for: App startup validation
#config#validation
typescriptbeginner
Type-Safe Configuration Loader
Load and validate configuration from environment variables with type coercion and required field checks.
Best for: Application configuration management
#nodejs#config
typescriptbeginner
Environment Variable Validation
Validate required environment variables at build time with type-safe access and descriptive errors.
Best for: App startup checks
#environment#validation
typescriptintermediate
Environment Variable Validation with Zod
Validate environment variables at build time using Zod to catch misconfigurations early.
Best for: build-time validation
#nextjs#env