Environment & Config — Node.js

Config is the values that differ between machines (port, database, secrets, mode). Config is read from environment variables (NAME=value pairs from outside…

The notes-api repo on GitHub contains the line const JWT_SECRET = "super-secret";. Anyone who can read that repo can now make their own admin token. The second problem: when you deploy (put the app on a server), the port and database address on the server differ from your laptop's. So the code has to be edited every time it moves to another machine.

Values that differ between your laptop and the server are called config: the port, the database address, the secret for JWT (a secret value used to sign tokens), and the app's mode. Config values aren't written in the code. They come from outside through environment variables: NAME=value pairs a program receives when it starts. The code is the same on every machine, and only the environment differs, meaning the set of environment variables on that machine.

process.env: values from outside the code

In Node, every environment variable is in the object process.env. This is the part of notes-api's app.js that reads the port from the environment:

const port = Number(process.env.PORT) || 3000;
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

Run it twice, once without PORT and once with PORT=8080:

$ node app.js
Server running at http://localhost:3000
$ PORT=8080 node app.js
Server running at http://localhost:8080

The values are always text

What process.env holds is always a string, even when it looks like a number or a boolean:

Code Result
process.env.PORT "3000"
process.env.PORT + 1 "30001"
Number(process.env.PORT) + 1 3001
process.env.DEBUG with DEBUG=false "false", which counts as true in an if

process.env.PORT + 1 becomes "30001", because + joins text, it doesn't add. Convert first with Number(...). For a boolean, compare with the text directly: process.env.DEBUG === "true".

The .env file and three ways to load it

Typing every variable in front of node each time is tiring. While developing (building and trying the app on your laptop), put the values in a .env file in the project's main folder:

# .env for notes-api (never commit it)
NODE_ENV=development
PORT=3000
DATABASE_URL=postgres://budi:secret@localhost:5432/notes

Node doesn't read this file automatically. There are three ways to load it into process.env:

  1. node --env-file=.env app.js: built into Node 20.6 and later, nothing to install.
  2. process.loadEnvFile(); on the very first line: built into Node 20.12 and later. This function reads the .env in the folder you run node from.
  3. The dotenv package: npm install dotenv, then require("dotenv").config(); on the very first line. This is the classic way, which works on any Node version.

All three use the same format: one NAME=value per line, # for comments, and quotes are allowed for a value with spaces in it.

Who wins: the shell or .env

A variable already in the environment wins over the file, both with --env-file and with dotenv:

$ PORT=8080 node --env-file=.env app.js
Server running at http://localhost:8080

.env holds 3000, the shell sets 8080, and 8080 is used. This is on purpose. On a server, values are set by the hosting (the service where the app runs) or by systemd (the service manager on a Linux server). Those values must not be overwritten by a .env file that happened to be uploaded too.

NODE_ENV: development or production

NODE_ENV is the agreed name for the app's mode:

One config file, checked at start

Read every variable in one file, and refuse to start when a required variable is empty:

// config.js
const required = ["DATABASE_URL", "JWT_SECRET"];
const missing = required.filter((name) => !process.env[name]);
if (missing.length > 0) {
  console.error(`Config error: ${missing.join(", ")} not set. Copy .env.example to .env, then fill it in.`);
  process.exit(1);
}

module.exports = {
  env: process.env.NODE_ENV || "development",
  port: Number(process.env.PORT) || 3000,
  databaseUrl: process.env.DATABASE_URL,
  jwtSecret: process.env.JWT_SECRET,
};

With the .env above, which has no JWT_SECRET yet, this is the result. echo $? prints the exit code of the command before it:

$ node --env-file=.env app.js
Config error: JWT_SECRET not set. Copy .env.example to .env, then fill it in.
$ echo $?
1

Secrets never go into git

This is an example .env.example:

# .env.example (committed)
NODE_ENV=development
PORT=3000
DATABASE_URL=
JWT_SECRET=

In the exercise: config per environment

In the exercise, the starter code already sets process.env.PORT = "3000". It also has a config object that holds development (port 3000, logLevel: "debug") and production (port 8080, logLevel: "warn"). You write two functions:

In the exercise simulator, DATABASE_URL isn't set, so the last line is Env check: {"valid":false,"missing":["DATABASE_URL"]}.

⚠️ Config that's quietly wrong

TL;DR: Config is the values that differ between machines (port, database, secrets, mode). Config is read from environment variables (NAME=value pairs from outside the program) through process.env, not written in the code. The values are always strings: process.env.PORT + 1 gives "30001", so use Number(...). A .env file (where the values live while you develop on your laptop) is loaded with node --env-file=.env app.js (Node 20.6+), process.loadEnvFile(), or the dotenv package. A variable already in the environment wins over the file. NODE_ENV=production changes how Express and npm behave. Read the config in one file, check the required variables at start, then process.exit(1) with a clear message if one is empty (fail fast). .env is written in .gitignore so it is not committed, .env.example is what gets committed, and a secret is never in the code.

⚡ Config comes from outside the code

Write:

const port = Number(process.env.PORT) || 3000;
Guess first: PORT isn't set at all. Which port is used?

Port 3000. process.env.PORT holds undefined, so || 3000 is used.

Meaning: Values that differ between your laptop and the server, such as the port, the database address and the JWT secret, are called config. Config is given through environment variables, NAME=value pairs from outside the program. In Node, they all live in the object process.env, and the values are always strings.

⚡ A .env file, never committed

Write:

node --env-file=.env app.js

Meaning: While developing (building and trying the app on your laptop), put the config values in a .env file and load it with --env-file (Node 20.6 and up) or the dotenv package. .env is written in .gitignore, so it is not committed. Only .env.example, with empty values, is committed.

⚡ Stop when something isn't set

Write:

const required = ["DATABASE_URL", "JWT_SECRET"];
const missing = required.filter((name) => !process.env[name]);
if (missing.length > 0) {
  process.exit(1);
}

Meaning: Check every required variable at startup, and collect all the empty ones, not only the first one. process.exit(1) ends the program with the sign of failure. This is called fail fast: failing in the first second with a clear message is better than a server that starts and then throws a strange error at the first login.

What you will learn