Node.jsintermediate 8 min
Keep secrets and settings out of your code with process.env and .env files.
What environment variables are, how to read them with process.env, how to load them from a .env file, and why secrets must never be committed to git.
Your app needs settings that change between your laptop and the live server (port, database address) and secrets that must never be public (API keys, passwords). If you write them into the code and push to GitHub, anyone can read them. Environment variables keep them outside the code.
An environment variable is a named value that belongs to the environment a program runs in, not to the code. In Node you read it with process.env.NAME. Values are always strings, or undefined if not set.
You can set them when starting the program:
More convenient is a .env file that lists them:
Modern Node (version 20.6 and newer) can load it with a flag, no package needed:
Or from code with process.loadEnvFile(".env") (Node 21.7 and newer).
Rules to follow:
.env to .gitignore. Commit a .env.example listing the names without real values.process.env.PORT ?? 3000.Number(process.env.PORT)..env file so the demo is self-contained.process.loadEnvFile(".env") reads it and copies the values into process.env.process.env.PORT is the string "4000", so typeof prints string. We convert with Number(...) and add 1: 4001.DEBUG=true is also a string. We compare with "true" to get a real boolean.SECRET_KEY is not set, so it is undefined and Boolean(...) is false.Run it on your computer (Node 21.7 or newer), then add SECRET_KEY=shh to the written file text and see secret set change to true.
.env to git. Add it to .gitignore immediately."false" is truthy.process.env; they are strings..env file with --env-file or process.loadEnvFile..env out of git and give harmless settings defaults.Next: middleware.
PORT=4000 node app.js # macOS / Linux
$env:PORT=4000; node app.js # Windows PowerShellPORT=4000
API_KEY=abc123node --env-file=.env app.jsimport { writeFileSync } from "node:fs";
// Create a .env file for this demo
writeFileSync(".env", "PORT=4000\nAPP_NAME=LearnStack\nDEBUG=true\n");
process.loadEnvFile(".env");
const port = Number(process.env.PORT ?? 3000);
const name = process.env.APP_NAME ?? "App";
const debug = process.env.DEBUG === "true";
const missing = process.env.SECRET_KEY;
console.log(typeof process.env.PORT, port + 1);
console.log(name);
console.log("debug:", debug);
console.log("secret set:", Boolean(missing));