Environment variables and configuration

Topic 2 of 5 in The Node runtime6 min readIntermediateFree course

Overview

Your app runs in several places: your laptop, a teammate’s laptop, a test server, production. Each needs different settings — a different database, a different port, different API keys. And some of those settings are secrets that must never appear in your code or your Git history.

The standard solution is environment variables: named values that the operating system passes to a process when it starts. This idea is a core part of the well-known Twelve-Factor App guidelines: store config in the environment.

Reading environment variables

JavaScript
console.log(process.env.HOME);     // '/home/asha'
console.log(process.env.PORT);     // '3000' or undefined

Set them when starting the program:

Terminal
PORT=4000 NODE_ENV=development node server.js        # macOS / Linux
$env:PORT=4000; node server.js                       # Windows PowerShell

Two things to remember:

  • Every value is a string (or undefined if it isn’t set). PORT is '4000', not 4000; DEBUG=false is the string 'false', which is truthy. Always convert.
  • Missing values are undefined, so provide defaults with ??.
JavaScript
const port = Number(process.env.PORT ?? 3000);
const debug = process.env.DEBUG === 'true';

.env files

Typing variables on every run gets old quickly. During development, keep them in a .env file in the project root:

Text
# .env — local development only. Never commit this file.
PORT=3000
NODE_ENV=development
DATABASE_URL=postgres://app:secret@localhost:5432/academy
JWT_SECRET=dev-only-change-me

Node can load it for you:

Terminal
node --env-file=.env src/server.js

Or from code, early in your entry file: process.loadEnvFile(). Before this was built in, projects used the dotenv package — you’ll still see import 'dotenv/config' in many codebases, and it works the same way.

Variables already set in the real environment take priority over the file, so a hosting platform’s settings always win.

Protect your secrets

  • Add .env to .gitignore before your first commit.
  • Commit a .env.example with every variable name and safe placeholder values, so new developers know what to set:
Text
PORT=3000
DATABASE_URL=postgres://user:password@localhost:5432/dbname
JWT_SECRET=
  • In production, set real values in your hosting platform’s settings, Docker or Kubernetes secrets, or a secrets manager — not in a file inside the image.

If a secret is ever committed, treat it as leaked: rotate it (create a new one and revoke the old) immediately. Deleting the line later doesn’t remove it from Git history.

One config module

Scattering process.env.SOMETHING across dozens of files causes problems: typos go unnoticed, conversions are repeated, and a missing variable only crashes the app hours later when that code finally runs. Instead, read everything once, in one place, at start-up:

Configuration comes first from real environment variables set by your host, Docker or CI, then from a local .env file used only in development, then from defaults in config.js. The first match wins, and config.js produces a validated, typed, frozen object. Read and check everything at start-up and crash early if a required value is missing.

JavaScript
// src/config.js
const required = (name) => {
  const value = process.env[name];
  if (!value) throw new Error(`Missing required environment variable ${name}`);
  return value;
};

export const config = Object.freeze({
  env: process.env.NODE_ENV ?? 'development',
  port: Number(process.env.PORT ?? 3000),
  databaseUrl: required('DATABASE_URL'),
  jwtSecret: required('JWT_SECRET'),
  corsOrigin: process.env.CORS_ORIGIN?.split(',') ?? ['http://localhost:5173'],
});

Everything else imports config:

JavaScript
import { config } from './config.js';
app.listen(config.port);

Now a missing DATABASE_URL stops the app immediately with a clear message, instead of failing on the first database query. This is called failing fast, and it turns confusing production incidents into obvious deployment errors.

For larger apps, a validation library such as Zod (covered in Validating input) can describe and check the whole config in one schema.

NODE_ENV

NODE_ENV is a long-standing convention for saying which environment you’re in, usually development, test or production. Many libraries read it — Express, for example, hides error details and enables caching when it’s production.

Set NODE_ENV=production on production servers. But don’t use it for your own settings (“if production, use this database”) — give each setting its own variable instead. That keeps environments like “staging” from needing special cases.

What belongs where

Setting Where it lives
Database URL, API keys, JWT secret environment variable (secret)
Port, log level, allowed origins environment variable with a default
Page size, password rules, feature lists code (they change with the code, not the environment)

A useful test: could you open-source the codebase right now without leaking anything? If yes, your config is in the right place.

Exercise

A config module

Write config.js that reads PORT (default 3000, must be a number), DATABASE_URL (required) and NODE_ENV (default 'development'). It should throw a clear error listing every missing or invalid value, and export a frozen object.

JavaScript
// config.js
const env = process.env;

Summary

  • Configuration that changes between environments — ports, URLs, secrets — belongs in environment variables, not code.
  • Read them from process.env; every value is a string or undefined.
  • Load a local .env file with node --env-file=.env; never commit it, but do commit .env.example.
  • Read and validate all config once at start-up, in one module, and fail fast.
  • NODE_ENV=production changes how many libraries behave.