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
process.env.PORTreads the variablePORT. When it isn't set, the result isundefined, and|| 3000uses 3000.PORT=8080 node app.jssetsPORTfor that one run only. This works in the bash and zsh shells (the terminal program that runs your commands), on Linux, macOS and Git Bash. In PowerShell:$env:PORT=8080; node app.js.- Same code, different result. That's the goal: what changes between machines is kept in the environment.
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:
node --env-file=.env app.js: built into Node 20.6 and later, nothing to install.process.loadEnvFile();on the very first line: built into Node 20.12 and later. This function reads the.envin the folder you runnodefrom.- The dotenv package:
npm install dotenv, thenrequire("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:
- With
NODE_ENV=production, Express's built-in error page shows no stack trace (the Error Handling lesson). Templates (files that build HTML pages) are also cached, meaning they are kept so they aren't read again on every request. npm installandnpm ci(the install command usually used on servers) withNODE_ENV=productionskip thedevDependencies(packages installed with-D), such as the test tools from the Testing API lesson.- In your code:
const isProduction = process.env.NODE_ENV === "production";. Write exactlyproduction, because libraries only check that word, notprod.
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
required.filter((name) => !process.env[name])collects every empty name, instead of stopping at the first.process.exit(1)ends the program with exit code 1, 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, at 2 a.m.- Other files only need
const config = require("./config");, and then useconfig.port, without touchingprocess.envagain. - For more rules (must be a number, must be a URL), libraries such as
zodorenvalidcheck the variables against a schema.
Secrets never go into git
.envis written in.gitignore(the list of files that are not committed). What gets committed is.env.example: only the names, no values, so teammates know what to fill in.- On the server, the values are set in the hosting dashboard, in a systemd unit, or in PM2 (the Deploy Node.js lesson that comes next).
const config = { dbPassword: "secret123" }in the code means the secret is stored in git history (the record of commits), in every clone (copy of the repo). What to do once it has leaked is in the Environment Variables & Secrets lesson of the Security track.
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:
getConfig(env), which returnsconfig[env] || config.development.validateEnv(required), which usesfilterwith!process.env[key], then returns{ valid: missing.length === 0, missing }.
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
- Forgetting the values are text.
process.env.PORT + 1becomes"30001", andifstill treatsDEBUG=falseas true. - Loading
.envtoo late. Ifrequire("dotenv").config()is placed afterrequire("./config"), the config readsundefined. Load.envon the very first line. - A typo in a name.
process.env.PROT || 3000quietly gives 3000. Therequiredlist checked at start catches typos in required variables. - A secret in the code, or
.envcommitted. Once it is in git, treat that secret as leaked.
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.