Code Reference

Environment & Config

Node.js · Reference cheat sheet

Environment & Config

Node.js · Reference cheat sheet


📋 Overview

Configure Node apps with environment variables, optionally loaded from .env files via dotenv or platform secrets. Validate required keys at startup.

🔧 Core concepts

SourceUse
process.envPrimary config bag
.env + dotenvLocal development
Host secretsProduction (Vercel, Docker, K8s, etc.)
NODE_ENVdevelopment / production / test
PracticeWhy
Fail fastCrash if required vars missing
No secrets in repoUse .env.example templates only
Typed config moduleSingle parse point

💡 Examples

Fail-fast config:

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

export const config = {
  port: Number(process.env.PORT || 9000),
  databaseUrl: required("DATABASE_URL"),
};

dotenv (dev):

import "dotenv/config";

.env.example:

PORT=9000
DATABASE_URL=postgres://user:pass@localhost:5432/app

⚠️ Pitfalls

  • process.env values are strings — PORT needs Number(...).
  • Loading .env in production can accidentally override platform secrets if misordered.
  • Never log raw env objects — they often contain credentials.

On this page