Environment variables and configuration
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
console.log(process.env.HOME); // '/home/asha'
console.log(process.env.PORT); // '3000' or undefinedSet them when starting the program:
PORT=4000 NODE_ENV=development node server.js # macOS / Linux
$env:PORT=4000; node server.js # Windows PowerShellTwo things to remember:
- Every value is a string (or
undefinedif it isn’t set).PORTis'4000', not4000;DEBUG=falseis the string'false', which is truthy. Always convert. - Missing values are
undefined, so provide defaults with??.
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:
# .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-meNode can load it for you:
node --env-file=.env src/server.jsOr 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
.envto.gitignorebefore your first commit. - Commit a
.env.examplewith every variable name and safe placeholder values, so new developers know what to set:
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:
// 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:
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.
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.
// config.js
const env = process.env;// config.js
const env = process.env;
const errors = [];
const port = Number(env.PORT ?? 3000);
if (!Number.isInteger(port) || port <= 0) errors.push('PORT must be a positive whole number');
if (!env.DATABASE_URL) errors.push('DATABASE_URL is required');
if (errors.length) {
throw new Error(`Invalid configuration:\n- ${errors.join('\n- ')}`);
}
export const config = Object.freeze({
port,
databaseUrl: env.DATABASE_URL,
env: env.NODE_ENV ?? 'development',
isProduction: env.NODE_ENV === 'production',
});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 orundefined. - Load a local
.envfile withnode --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=productionchanges how many libraries behave.