AceDevHub
Beginner Node.js Interview QuestionsBeginnerConcept

Node.js · Question 23

How do environment variables work in Node.js?

Direct answer

process.env is an object of string key-value pairs inherited from the shell and deployment platform — use it for PORT, DATABASE_URL, and secrets; validate at startup and never commit secrets to git.

Why interviewers ask this

Config via env vars keeps twelve-factor apps portable — same Docker image runs in local, staging, and prod with different env injection (Compose, Kubernetes, Hetzner).

  • All strings — process.env.PORT is "4000" not number; coerce with Number() or validation lib.
  • NODE_ENV — convention: development | test | production; frameworks tune logging/cache.
  • .env files — dotenv loads into process.env in dev only; prod uses real env (Q48).
  • Secrets — never log process.env in production; redact in error reports.
env-config.mjs
function requireEnv(name) {
  const value = process.env[name];
  if (!value) throw new Error(`Missing required env: ${name}`);
  return value;
}

const config = {
  port: Number(process.env.PORT ?? 4000),
  databaseUrl: requireEnv("DATABASE_URL"),
  nodeEnv: process.env.NODE_ENV ?? "development",
};

export default config;