Sub topic 5
Using a .env file for local development
This chapter assumes you can use a terminal, know what an environment variable is (the previous chapter covered export), and can read short Python or JavaScript snippets. It covers the .env file: what it is, how its syntax works, how code loads it, and where it goes wrong. Keeping it out of Git is the next chapter's topic. Here we only note why that matters.
Why a .env file exists
An export command sets a variable for one shell session. Close the terminal and the variable is gone. You can put export lines in a shell profile such as ~/.bashrc, but then every program you start in that shell sees the key, and the setting is shared across all your projects.
A .env file solves this by keeping the variables next to the project that needs them. It is a plain text file with one KEY=value pair per line. Your application, or a small library, reads the file at startup and copies those pairs into the process environment. After that, the code reads the key exactly as it would read any other environment variable.
# .env
LLM_API_KEY=paste-your-key-hereThe file is a convenience for local development only. It is still a file on disk holding a secret in plain text, so it deserves the same care as a password written on paper.
How the file is read
The flow has three steps. The loader finds .env, parses each line, and writes the values into the process environment. Your code then reads them with the normal environment API.
The diagram shows two sources feeding the same environment. The second source, real environment variables, matters because of the precedence rule below.
Syntax rules
Most loaders follow the same basic format. Details differ slightly between libraries, so check the documentation of the one you use.
- One
NAME=valuepair per line, with no spaces around=in the safest style. - Lines starting with
#are comments. - Blank lines are ignored.
- Quotes are optional. Use them if the value contains spaces or a
#, which some loaders would otherwise treat as the start of a comment. - Names are conventionally uppercase with underscores.
- Do not add
exportin front unless your loader documents support for it. Many do, but you gain nothing by relying on it.
# .env
# Provider key for local testing only
LLM_API_KEY=paste-your-key-here
LLM_MODEL=example-model-name
LLM_TIMEOUT_SECONDS=30Every value in a .env file is a string. LLM_TIMEOUT_SECONDS=30 arrives in your code as "30", so convert it with int() or Number() when you need a number.
Loading it in Python
The python-dotenv package reads the file for you. Install it with pip install python-dotenv.
import os
from dotenv import load_dotenv # pip install python-dotenv
load_dotenv() # reads .env into os.environ; real environment variables are not overridden by default
api_key = os.environ.get("LLM_API_KEY")
if not api_key:
raise RuntimeError("LLM_API_KEY is not set")Three details are worth understanding.
load_dotenv()searches for a.envfile starting from the directory of the calling script and moving up through parent folders. If it finds none, it does nothing and does not raise an error. That is why the explicit check afterward is important.- By default it does not override variables that already exist in the environment. If
LLM_API_KEYis set in your shell, the shell value wins over the file. - Call it once, early, before any code that reads the key. Reading the variable first and loading the file afterward gives you
None.
You can pass an explicit path with load_dotenv(".env.local"). This is useful when you keep separate files for separate setups.
Loading it in Node.js
Node.js can read a .env file without a library in recent versions, using the --env-file flag:
node --env-file=.env app.jsOlder setups use the dotenv package, which you call at the top of your entry file with require("dotenv").config(). Check which Node version you run before choosing. After either method, the code is the same:
const apiKey = process.env.LLM_API_KEY;
if (!apiKey) {
throw new Error("LLM_API_KEY is not set");
}Precedence: which value wins
When the same name appears in the shell and in .env, the loader decides. With python-dotenv defaults, the shell wins. This is useful: on a server or in CI, the real environment variable overrides whatever file might be present, so a stray .env cannot silently replace the production key.
It also causes a common confusion. Suppose you edit .env to paste a new key, but your shell still has an old export LLM_API_KEY=... from earlier. Your program keeps using the old key, and you see authentication errors that make no sense. If a change to .env has no effect, check the shell first.
echo "${#LLM_API_KEY} characters set"
unset LLM_API_KEYThe first line prints only the length, so you can see whether the variable exists without exposing it. The second line removes it from the current shell so the file value takes effect.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `LLM_API_KEY is not set` | `.env` is in a different directory than the one the loader searches | Run from the project root or pass the file path explicitly |
| Key is set but the provider returns 401 | Extra space, stray quote, or a trailing newline copied with the key | Re-copy the key and remove whitespace around `=` and inside quotes |
| Old key still used after editing `.env` | A shell variable overrides the file | Run `unset LLM_API_KEY` and restart the program |
| Value is `None` at import time | The key was read before the loader ran | Call `load_dotenv()` before reading the variable |
| Number setting behaves oddly | Value is a string such as `"30"` | Convert explicitly |
| Value is cut off after a `#` | The loader treated `#` as a comment start | Wrap the value in quotes |
File naming and multiple environments
A common convention is a small family of files:
.envholds your real local values. It is never committed..env.examplelists the variable names with fake placeholder values. It is committed so teammates know what to set..env.localor.env.testhold variants for specific situations.
# .env.example
LLM_API_KEY=your-key-goes-here
LLM_MODEL=example-model-nameThe example file must never contain a real key. A frequent mistake is to copy .env to .env.example and forget to blank out the secret. Because .env.example is committed on purpose, that mistake publishes the key.
Where a .env file does not belong
The .env file is for your own machine. Avoid these uses:
- Production servers. Use the host's environment variable or secret settings instead. Production should not depend on a file that someone has to place correctly by hand.
- Docker images. Copying
.envinto an image withCOPY . .bakes the key into a layer that anyone with the image can read. Pass variables at run time instead, and consider a.dockerignoreentry for.env. - Browser code. A bundler may expose some variables to client-side code, and anything exposed there is visible to every visitor. Keys belong on the server.
- Shared folders and chat. Do not paste the file into a team chat or sync it through a shared drive.
Checking your setup safely
After loading, verify the key exists without printing it. Print the length, or whether it is set, but never the value.
import os
from dotenv import load_dotenv
load_dotenv()
key = os.environ.get("LLM_API_KEY", "")
print(f"LLM_API_KEY set: {bool(key)}, length: {len(key)}")Avoid debugging by printing os.environ as a whole. That dumps every secret on the machine into your terminal and possibly into log files.
Summary of the working model
A .env file is a text file of KEY=value lines. A loader copies it into the process environment at startup, and real environment variables take priority. Your code never needs to know where the value came from. That separation is the point: the same code runs on your laptop with a .env file and on a server with real environment variables.
Exercise
You edit .env to paste a new API key, but your program still sends the old one and the provider rejects it. Name the most likely cause, and give one command that checks it without revealing the key.
Show answer
A variable named LLMAPIKEY is still set in the shell from an earlier export, and by default python-dotenv does not override existing environment variables, so the old shell value wins. Run echo "${#LLM_API_KEY} characters set" to see whether it exists (it prints only the length), then unset LLM_API_KEY and restart the program.
Exercise
A teammate copies .env to .env.example so others know which variables to set, then commits both files. What went wrong, and what should .env.example contain?
Show answer
The copy still holds the real key, and .env.example is meant to be committed, so the key is now in the repository. .env.example should list only the variable names with fake placeholder values such as your-key-goes-here. The exposed key must also be revoked, because it remains in Git history.