Sikau

Node.js · Day 13 · about 25 min

Configuration and environments

Settings from the environment, validated at startup.

Same code, different places

Your API runs on your laptop, in tests and in production — with different ports, databases and keys. Keep code the same and pass settings through environment variables. Check them once at startup, so a missing secret fails loudly instead of at 3 a.m.

A config module

function required(name) {
  const value = process.env[name];
  if (!value) throw new Error(`Missing environment variable ${name}`);
  return value;
}

export const config = {
  port: Number(process.env.PORT ?? 3000),
  env: process.env.NODE_ENV ?? "development",
  databaseUrl: process.env.DATABASE_URL ?? "file:./dev.db",
  isProd: process.env.NODE_ENV === "production",
};

console.log(config);
try {
  required("STRIPE_KEY");
} catch (e) {
  console.log(e.message);
}
  • Locally, keep values in a .env file (add it to .gitignore!) and load it with node --env-file=.env server.js.
  • Commit a .env.example listing the variable names without real values.
  • Libraries like Zod can validate the whole config object with clear errors.

The rest of this lesson

  • Twelve-factor configurationexplain
  • Secrets in practiceexplain
  • What type?predict
  • String booleanspredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 18 lessons of Node.js