Skip to content

Environment variables and config

BasicsConcept

The same code runs on your laptop, in CI and in production, and each needs a different database and different keys. Here is how to keep those values out of the code, and the secrets out of git.

01 One codebase, many places to run

A value that changes between places your code runs is config: the database URL, the port, an API key, the log level. Written into the source, it forces a code change per environment and puts every secret in the repository, where everyone with read access, and every clone, has it.

Hard-coded
const db = new Pool({
connectionString: 'postgres://admin:hunter2@db.prod/shop',
});
From the environment
const db = new Pool({
connectionString: process.env.DATABASE_URL,
});

The code stays the same everywhere; each place supplies its own values. The widely used Twelve-Factor App guidelines put it simply: store config in the environment.

02 What an environment variable is

Every process on Linux, macOS and Windows carries a list of NAME=value strings. When one process starts another, the child gets a copy of the parent’s list, plus anything set for that command. In Node the list is process.env.

The shell starts node server.js. The new process gets its own copy of the shell’s variables.
Shell’s environment
HOME→/home/anaPATH→/usr/local/bin:/usr/binDATABASE_URL→postgres://localhost/shop_dev
node server.js · process.env (a copy)
HOME→/home/anaPATH→/usr/local/bin:/usr/binDATABASE_URL→postgres://localhost/shop_devread by configPORT→4000this command only
  • set for one command
  • read by the app

PORT=4000 node server.js adds PORT to the child only. Changes made inside Node never flow back to the shell, and changes in the shell after start never reach the running process.

Shell
$ PORT=4000 node server.js
Listening on 4000, debug false

03 Every value is a string

The operating system stores only text. process.env.PORT is "4000", not 4000, and a variable that was never set is undefined.

Shell
$ DEBUG=false node -e 'console.log(typeof process.env.DEBUG, Boolean(process.env.DEBUG))'
string true

DEBUG=false turns debugging on if you write if (process.env.DEBUG): "false" is a non-empty string, so it is truthy. Compare with the exact text, process.env.DEBUG === 'true'.

04 Read it once, check it at start

Scattering process.env.X through the code hides which settings the app needs, and a missing one surfaces only when that line runs, perhaps hours later. Read everything in one module, convert the types, and refuse to start if something required is missing.

config.js
function required(name) {
const value = process.env[name];
if (value === undefined || value === '') {
throw new Error(`Missing environment variable ${name}`);
}
return value;
}
const config = {
port: Number(process.env.PORT ?? 3000),
databaseUrl: required('DATABASE_URL'),
debug: process.env.DEBUG === 'true',
};
module.exports = Object.freeze(config);
server.js
const config = require('./config');
console.log(`Listening on ${config.port}, debug ${config.debug}`);
Shell
$ node server.js
/app/config.js:4
throw new Error(`Missing environment variable ${name}`);
^
Error: Missing environment variable DATABASE_URL

Crashing at start is the friendly outcome: the deploy fails at once, with the variable’s name in the log, instead of the app half-working.

05 A .env file for your own machine

Typing every variable before each command gets old. On your laptop, put them in a .env file. Since Node 20.6, node --env-file=.env loads it before your code runs; on older versions the dotenv package does the same job.

.env
PORT=3000
DATABASE_URL=postgres://localhost:5432/shop_dev
DEBUG=false
Shell
$ node --env-file=.env server.js
Listening on 3000, debug false
$ PORT=4000 node --env-file=.env server.js
Listening on 4000, debug false

The second run shows the rule: a variable already set in the real environment wins over the file. That is what lets a server or CI override your defaults. dotenv behaves the same way unless you ask it to override.

Keep the real file out of git, and commit a copy with the names but no secret values, so the next person knows what to fill in:

.gitignore
.env
.env.example
PORT=3000
DATABASE_URL=
DEBUG=false

06 Where each environment gets its values

Only your laptop should read a .env file. Everywhere else, the thing that starts your process sets the variables, and secrets come from a store built for them.

Who supplies the variables
EnvironmentSettings come fromSecrets come from
Your laptopA git-ignored .env fileThe same file, with dev-only credentials
CIVariables in the pipeline configThe CI system’s secret settings, masked in logs
Production containerdocker run -e, or the orchestrator’s configA secret manager (for example Kubernetes Secrets or a cloud secret store), injected at start
SettingsFine in gitPORT, LOG_LEVEL, timeouts. Safe to commit as defaults and override per environment.
SecretsNever in gitPasswords, API keys, signing keys. Each environment has its own, so a leaked dev key does not open production.

07 When it goes wrong

git add .envA committed secretDeleting the file in the next commit leaves it in history and in every clone. Rotate the secret: issue a new one and revoke the old.
console.log(process.env)Secrets in the logsDumping the environment, or a config object, while debugging copies every secret into your log system. Log the names, not the values.
ENV DB_PASSWORD=hunter2Secrets baked into an imageA Dockerfile ENV is stored in the image, and anyone who can pull it can read it with docker inspect. Pass secrets when the container starts.
VITE_API_KEY=sk_live_…Front-end “env vars” are publicBundlers such as Vite and Next.js copy prefixed variables into the JavaScript sent to every visitor. Only public values belong there.
PORT changed, app not restartedExpecting a live updateA process gets its copy once, at start. Change a variable and you must restart the process to see it.

08 Check yourself

Question

You run DEBUG=false node app.js, and the code says if (process.env.DEBUG) enableDebug(). Does debugging turn on?

Question

.env says PORT=3000. You run PORT=4000 node --env-file=.env server.js. Which port does it use?

Question

You pushed a .env with a live database password, then removed it in the next commit. What now?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?