When in Doubt, Crash


The Problem
If you’ve set up an existing codebase on your local machine before, you may know the pain of transferring and setting up ENV variables. Sometimes we have an ENV template, but they often go stale if someone forgot to update it even once.
Or, perhaps you have an existing codebase you work with and a merge was made while you were gone and you missed the Slack messages about the new ENV.
Long-story-short, sometimes we are missing ENV vars.
Now, this wouldn’t be the biggest problem in the world if the app would just crash. Unfortunately, many developers (and I’ve noticed AI) love to give a fallback value.
Warning: Insidious Fallback
export function getApiUrl(): string {
return process.env.API_URL || "http://localhost:3000"; // <-- insidious fallback
}
If this ended up on production, some very strange results would occur. But, would it be noticed right away?
The Solution
The correct solution would be to have something like this before every ENV variable:
let apiUrl: string;
try {
const value = process.env.API_URL;
if (!value) {
throw new Error("Missing required environment variable: API_URL");
}
apiUrl = value;
} catch (err) {
console.error(err);
process.exit(1); // Or handle it in some other way
}
However,
The Better Solution
Create a requireEnv()
function that provides fail-fast protection, is clean, and provides good feedback. Here is the one I use in my own codebases:
/**
* Get a required environment variable or throw an error if it's not set
* @param name - The name of the environment variable
* @returns The environment variable value
* @throws Error if the environment variable is not set
*/
export function requireEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Required environment variable '${name}' is not set`);
}
return value;
}
And it is used like this
import { requireEnv } from "./requireEnv";
export const config = {
apiUrl: requireEnv("API_URL"),
dbPassword: requireEnv("DB_PASSWORD"),
};
Let’s say that API_URL
is not set, we get
Error: Required environment variable 'API_URL' is not set
Conclusion
Like the title says, when in doubt, crash—catch your missing env vars early!
Subscribe to my newsletter
Read articles from Brian Scramlin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Brian Scramlin
Brian Scramlin
I am a full-stack developer, CTO, and Engineering Manager from Battle Creek, MI. My focus is on enterprise TypeScript applications. I have worked with startups and legacy companies as a senior engineer and currently serve as CTO of Ministry Designs.