Skip to content

Instantly share code, notes, and snippets.

@gameshler
Created July 15, 2025 17:47
Show Gist options
  • Select an option

  • Save gameshler/61dd4b9de94a6131375c12b7f4fed785 to your computer and use it in GitHub Desktop.

Select an option

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.
/**
* 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