The same code runs on your laptop and on the server, but the database is different. How does the program know where it is running? From environment variables: NAME=value pairs that a program carries while it runs, such as HOME=/home/budi or APP_ENV=development. Programs read them to learn their settings: whether they run in development (still being built) or production (used by real users), and where the database is.
The way a program receives environment variables is like leaving your child at grandma's house with a photocopy of your list of instructions. The child only brings the instructions you wrote on that list, not everything in your head. And if the child scribbles on the photocopy, your own list doesn't change. Here, you are the shell, the child is the program you run, and the photocopy is the copy of the variables.
Shell variables: make one and read it
A variable is a name that holds a value:
$ NAME=Budi
$ echo "Hello $NAME"
Hello Budi
$ echo 'Hello $NAME'
Hello $NAME
$ NAME = Budi
bash: NAME: command not found
NAME=Budimakes a variableNAMEwith the valueBudiin the shell you're using. No spaces around the=.- The shell replaces
$NAMEwith its value before the command runs, soechoreceives the textHello Budi. - Inside double quotes (
"..."),$NAMEis still replaced. Inside single quotes ('...'),$NAMEisn't replaced, and it is shown as it is. NAME = Budiwith spaces is read as a command calledNAMEwith two arguments. That command doesn't exist, so the shell answerscommand not found.
Variable names are usually uppercase with underscores, such as APP_ENV or DB_HOST.
export: hand it to the programs you run
A program that is running is called a process. A program you start from the terminal, such as node app.js (it runs the JavaScript file app.js), is called a child process. Your shell is its parent (the parent process). A child process only gets a copy of the variables that have been exported.
The file app.js holds one line. process.env holds the environment variables that a Node.js program receives, so this line shows the value of APP_ENV:
console.log(process.env.APP_ENV);
Below, APP_ENV gets a value without export, then node app.js runs. Guess first what node app.js shows: development or undefined (no value)?
$ APP_ENV=development
$ echo $APP_ENV
development
$ node app.js
undefined
$ export APP_ENV
$ node app.js
development
APP_ENV=developmentonly makes a shell variable.echocan show it because the shell itself replaces$APP_ENV.node app.jsis a new process. Without export,APP_ENVisn't handed over, soprocess.env.APP_ENVisundefined.export APP_ENVmarks the variable to be handed over. From then on, every program you run from this shell gets a copy. You can make and export it at the same time:export APP_ENV=development.
Two more rules, still in the same shell (APP_ENV is now exported):
$ APP_ENV=production node app.js
production
$ echo $APP_ENV
development
$ bash -c 'export APP_ENV=staging'
$ echo $APP_ENV
development
NAME=value commandon one line gives that value only to that command.APP_ENVin your shell staysdevelopment.- A child process only holds a copy, so nothing it changes comes back to the parent.
bash -c '...'runs the command inside the quotes with a new bash, as a child process, so theexportin there doesn't touch your shell.
The export command and the NAME=value command form exist in bash and zsh, so you can use them on Linux, macOS, WSL and Git Bash. On Windows, PowerShell and Command Prompt (cmd, the older shell that comes with Windows) use other forms. In those two Windows shells, an environment variable you create goes straight to the programs you run, so there is no separate export step:
| Shell | Set a value | Read it |
|---|---|---|
| bash, zsh | export APP_ENV=development |
echo $APP_ENV |
| PowerShell | $env:APP_ENV = "development" |
$env:APP_ENV |
| cmd | set APP_ENV=development |
echo %APP_ENV% |
This difference matters for the scripts in package.json (the settings file of a Node.js project). A script there is a command with a name, and you run it with npm run. On Windows, npm run runs scripts with cmd, so the script "start": "APP_ENV=production node app.js" fails there. Two ways work on every system. One is the cross-env package (a library you install with npm): cross-env APP_ENV=production node app.js. The other is to put the value in a .env file, then run node --env-file=.env app.js (see the .env part below).
Built-in variables, PATH, and making it permanent
Some environment variables are already there when the terminal opens:
$ echo $HOME
/home/budi
$ echo $PATH
/usr/local/bin:/usr/bin:/bin
$ which node
/usr/local/bin/node
env(orprintenv) lists every environment variable, meaning the exported ones. Shell variables that haven't been exported don't appear.HOMEholds your home folder,USERyour user name,PWDthe folder you're in, andSHELLthe shell you use.PATHis a list of folders separated by:. When you typenode, the shell looks for a file callednodein those folders, starting from the one on the left, and runs the first one it finds.which nodetells you which one that is.- Adding a folder to PATH:
export PATH="$HOME/.local/bin:$PATH".$PATHis replaced by the old list, so the new folder is in front and the old list stays behind the:.
Every variable you make in the terminal is gone when the terminal closes. To make one permanent, put its export line in ~/.bashrc (bash on Linux) or ~/.zshrc (zsh, the default on macOS). The shell reads that file every time a terminal opens. In a terminal that is already open, run source ~/.bashrc (read it again) or open a new terminal.
The .env file in a project
An app's settings usually live in a .env file in the project folder:
# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME="mydb"
# App
APP_ENV=development
SECRET='s3cret'
- The shell doesn't read this file on its own. The app does: Laravel (a PHP framework) reads it automatically, and Node.js uses the
dotenvlibrary ornode --env-file=.env app.js(Node 20.6 and up). - The rules: one line holds one
KEY=VALUE(the key is the name, and the value is what it holds). A line starting with#is a comment (a note), blank lines are skipped, and quotes wrapped around a value are dropped. Every value is text,5432included. .envholds secrets, so don't commit it to Git (the tool that records your code's history). Add its name to.gitignore, the list of files Git ignores:echo ".env" >> .gitignore. Share a.env.examplewith just the names, no secret values.
Reading .env with JavaScript
In the exercise, you write the function parseEnvFile(content). It turns the contents of the .env file above (one string) into an object (a set of key and value pairs). One way to write it:
function parseEnvFile(content) {
const result = {};
for (const rawLine of content.split("\n")) {
const line = rawLine.trim();
if (line === "" || line.startsWith("#")) continue; // blank line or comment
const eq = line.indexOf("=");
if (eq === -1) continue; // not KEY=VALUE
const key = line.slice(0, eq).trim();
let value = line.slice(eq + 1).trim();
const first = value[0];
if ((first === '"' || first === "'") && value.endsWith(first)) {
value = value.slice(1, -1); // drop the wrapping quotes
}
result[key] = value;
}
return result;
}
What happens to each line of the .env above:
| Line | What happens | Goes into the object |
|---|---|---|
# Database |
a comment, skipped | (nothing) |
DB_HOST=localhost |
cut at the first = |
DB_HOST: "localhost" |
DB_PORT=5432 |
the value stays text | DB_PORT: "5432" |
DB_NAME="mydb" |
double quotes dropped | DB_NAME: "mydb" |
| (blank line) | skipped | (nothing) |
SECRET='s3cret' |
single quotes dropped | SECRET: "s3cret" |
With APP_ENV: "development" as well, the object has 5 keys. In the exercise, the result is stored in config, so Object.keys(config).length (the number of keys) is 5.
indexOf("=")only looks for the first=. So a value that contains=, such as the tokenabc==, stays whole.trim()removes spaces at the start and end, but spaces in the middle stay:B=two threebecomes"two three".
⚠️ Small slips that break variables
- Spaces around
=.APP_ENV = developmentdoesn't make a variable. The shell runs a command calledAPP_ENV, and that command doesn't exist. - Forgetting export. Your program gets
undefinedeven thoughechoshows the value. Check withenv | grep APP_ENV: if nothing appears, it isn't exported yet. - Overwriting PATH.
export PATH="$HOME/.local/bin"without:$PATHat the end throws away every old folder. Then commands likelsbecomecommand not founduntil you open the terminal again. - Committing
.env, or a parser that counts comments. A parser is code that reads a file, such asparseEnvFile. In the exercise,#lines and blank lines must not become keys (there must be5), wrapping quotes must be dropped (mydb,s3cret), and values with spaces must stay whole.
TL;DR: NAME=value (no spaces) makes a shell variable, and $NAME is replaced by its value, inside double quotes too, but not inside single quotes. For example, NAME=Budi; echo "Hello $NAME" prints Hello Budi (the ; separates two commands). A program you run from the shell (a child process) only gets a copy of the variables you export. Without export, process.env.APP_ENV in a Node.js program is undefined (no value). NAME=value command applies to that one command only, and a child process can't change the variables of the shell that started it. PATH is the list of folders the shell searches for programs. To make a variable permanent, put its export line in ~/.bashrc or ~/.zshrc. A .env file is read by the app, not by the shell: one KEY=VALUE per line, # for comments, wrapping quotes dropped, every value text, and never committed to Git.
⚡ Make a shell variable
Write:
NAME=Budi
echo "Hello $NAME"
Meaning: The first line makes a shell variable (a name that holds a value) called NAME with the value Budi. No spaces around =. The shell replaces $NAME with its value before the command runs, so echo prints Hello Budi. Inside single quotes, $NAME isn't replaced.
⚡ export: hand it to child processes
Write:
APP_ENV=development
node app.js
Guess first: node app.js runs app.js, which prints process.env.APP_ENV (the value of APP_ENV the program receives). What appears?
undefined (no value). Without export, the variable only exists in this shell and doesn't go along to the programs you run.
Meaning: export APP_ENV marks the variable to be handed over. After that, a program you run from this shell (a child process) gets a copy. Changes the child process makes don't come back to your shell.
⚡ PATH: where the shell looks for programs
Meaning: PATH is a built-in variable that holds a list of folders separated by :. When you type node, the shell looks for the program node in those folders, starting from the one on the left. To keep a variable after the terminal closes, put its export line in ~/.bashrc (bash on Linux) or ~/.zshrc (zsh): the shell reads that file every time a terminal opens.
⚡ The .env file
Write:
DB_HOST=localhost
DB_PORT=5432
DB_NAME="mydb"
Meaning: A .env file holds an app's settings. One line holds one KEY=VALUE (a name and its value), # marks a comment, and wrapping quotes are dropped. The app reads this file, not the shell. It holds secrets, so never commit it to Git.
In the exercise, comment lines and blank lines must not become keys.