Created
July 15, 2025 17:47
-
-
Save gameshler/61dd4b9de94a6131375c12b7f4fed785 to your computer and use it in GitHub Desktop.
A TypeScript utility to safely retrieve environment variables with optional fallbacks. Ensures critical environment variables are present and throws errors early when missing. Helps prevent runtime bugs due to undefined config.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Usage: | |
| * create a .env file containing the correct env names | |
| * export const PORT = getEnv("PORT"); | |
| * const DB_URL = getEnv("DATABASE_URL"); // throws if not defined | |
| */ | |
| const getEnv = (key: string, defaultValue?: string): string => { | |
| const value = process.env[key] || defaultValue; | |
| if (value === undefined) { | |
| throw new Error(`Environment variable ${key} is not defined`); | |
| } | |
| return value; | |
| }; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment