Env variables & config patterns
Configure apps with small defaults, safe env reads, and explicit objects. Avoid leaking secrets in the browser. Beginner-friendly patterns.
Big picture
Goal: Read config safely in any runtime.
- Defaults first
- Feature-detect env (do not assume process.env)
- Parse strings to numbers/booleans
- No secrets in browser bundles

Safe env read
Use feature detection to read env only when it exists. Provide a tiny demo store for runnable examples.
// Read an env var if available; otherwise use a fallback
function readEnv(name, fallback) {
// detect Node-like env
const hasProcessEnv = typeof process !== "undefined" && process && process.env && typeof process.env === "object";
if (hasProcessEnv && typeof process.env[name] === "string") {
return process.env[name];
}
// demo fallback store so this snippet runs everywhere
const DEMO = { API_URL: "https://api.example.com", NODE_ENV: "development" };
if (typeof DEMO[name] === "string") return DEMO[name];
return fallback;
}
console.log("API_URL:", readEnv("API_URL", "https://fallback.local"));

All lessons in this course
- Globals, fetch availability, file/network APIs
- ESM loader quirks, path/URL differences
- Env variables & config patterns