0Pricing
JavaScript Academy · Lesson

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
Env variables & config patterns — illustration 1

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"));
Env variables & config patterns — illustration 2

All lessons in this course

  1. Globals, fetch availability, file/network APIs
  2. ESM loader quirks, path/URL differences
  3. Env variables & config patterns
← Back to JavaScript Academy