Sub topic 7
Reading the key in your code
This chapter assumes you can use a terminal, have set an environment variable, and can read short Python or JavaScript snippets. It also assumes you have a key and a git-ignored .env file from the earlier chapters. The goal here is to get the key into your program without putting it in the source.
The rule: the code names the variable, never the value
Your source code should contain the name of the variable, such as LLM_API_KEY, and never the key itself. The value comes from the process environment when the program starts. This gives you three properties:
- The same code runs on your laptop, in CI, and in production with different keys.
- A copy of the repository contains no secret.
- Changing or revoking a key needs no code change and no new commit.
An environment variable is a name and value pair that the operating system hands to each process when it starts. Both Python and Node.js expose these pairs as a dictionary-like object: os.environ in Python and process.env in Node.js.
Where the value comes from
Your code only reads from the environment. Something else puts the value there, and the source depends on where the program runs.
Because the code reads only os.environ or process.env, it does not care which source filled it. This is why the same program works in all three places.
Reading the key in Python
The first version loads a .env file for local development and then reads the variable:
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")Two details matter here.
First, load_dotenv() does not override variables that already exist. If you exported LLM_API_KEY in your shell, the shell value wins over the .env value. This is usually what you want, because production settings then beat a stray local file. It can also confuse you when you edit .env and nothing changes. In that case check the shell with echo "${#LLM_API_KEY}". Pass override=True only if you want the file to win.
Second, if not api_key catches both a missing variable and an empty string. An empty value is a common failure, for example LLM_API_KEY= with nothing after the equals sign.
A small config module
Reading os.environ in many files spreads the secret handling around. Put it in one place and fail at startup:
import os
from dataclasses import dataclass, field
from dotenv import load_dotenv
load_dotenv()
@dataclass(frozen=True)
class Settings:
api_key: str = field(repr=False) # repr=False keeps the key out of print() and logs
model: str = "example-model"
def load_settings() -> Settings:
key = os.environ.get("LLM_API_KEY", "").strip()
if not key:
raise RuntimeError("LLM_API_KEY is not set or is empty")
return Settings(api_key=key)
if __name__ == "__main__":
print(load_settings()) # prints Settings(model='example-model') without the keyThis module does four things:
- It strips whitespace, so a trailing space or newline pasted into the value does not cause a 401 error.
- It fails when the program starts, not on the first request an hour later.
- It hides the key from the object's
repr, soprint(settings)or a logged exception that includes the object cannot leak it. - It gives the rest of the code one import to use.
Reading the key in JavaScript
In Node.js the pattern is the same:
const apiKey = process.env.LLM_API_KEY;
if (!apiKey) {
throw new Error("LLM_API_KEY is not set");
}Node.js does not read .env files by default in older versions. From Node 20.6 you can ask the runtime to load the file for you:
node --env-file=.env app.jsOn older versions, or if you prefer a library, install the dotenv package and call require("dotenv").config() before you read process.env. Check your Node version with node --version if the flag is rejected.
Using the key in a request
Most providers expect the key in an Authorization header as a bearer token. The URL below is a placeholder, so use the endpoint in your provider's documentation:
import os
import requests
api_key = os.environ["LLM_API_KEY"]
response = requests.post(
"https://api.example.com/v1/chat", # placeholder URL: use your provider's documented endpoint
headers={"Authorization": f"Bearer {api_key}"},
json={"prompt": "Say hello"},
timeout=30,
)
print(response.status_code)Here os.environ["LLM_API_KEY"] raises KeyError if the variable is missing. That is acceptable in a short script, but the error message only names the variable. The config module above gives a clearer message.
Some details to watch:
- Send the key in a header, not in the URL. Query strings end up in server logs, proxy logs, and browser history.
- Print the status code, not the response object's request headers.
response.request.headerscontains your key. - Always set a
timeout. Without one,requestscan wait forever.
Provider SDKs usually read a specific variable name on their own, and the name varies by provider. If you use an SDK, check its documentation for the variable name. You can still pass the key explicitly from your own variable, which makes the dependency visible in your code.
Mistakes that still leak the key
Reading from the environment is safe only if the value does not escape afterward. These are the common ways it escapes:
| Mistake | Why it leaks | Fix |
|---|---|---|
| `print(os.environ)` or `console.log(process.env)` to debug | Dumps every variable, including the key, into the terminal and any log capture | Print only the specific variables you need, and never the key |
| Logging the full request or response object | Headers carry the key | Log the status code, the request ID, and the error message |
| Putting a default in the code: `os.environ.get("LLM_API_KEY", "sk-real-key")` | The fallback is a hard-coded key in the source | Use no default for secrets. Fail instead |
| Error messages that include config | Stack traces and crash reporters can capture local variables | Keep the key in a `repr=False` field and avoid formatting it into strings |
| Passing the key on the command line: `python app.py --key abc` | It shows in shell history and in the process list | Use the environment or a file |
| Copying the real `.env` into a Docker image with `COPY . .` | The key is baked into an image layer that anyone with the image can read | Add `.env` to `.dockerignore` and pass the value at run time |
Read once, pass it down
Read the key at startup and hold it in one object. Avoid calling os.environ deep inside helper functions. A single read has these benefits:
- Missing configuration shows up immediately.
- Tests can pass in a fake key without touching the real environment.
- A reviewer can search for one place where the secret is handled.
In tests, never use a real key. Set a dummy value and mock the HTTP call:
import os
os.environ["LLM_API_KEY"] = "test-key-not-real"In pytest, monkeypatch.setenv("LLM_API_KEY", "test-key-not-real") does the same and restores the original value after each test.
Troubleshooting
When the key does not load, check these in order:
- Is the variable set in the same process? A key exported in one terminal tab is not visible in another tab or in an IDE that was already running.
- Is the
.envfile in the directory you start the program from?load_dotenv()searches from the calling file's location upward, but other loaders look only at the current working directory. - Is the line formatted as
LLM_API_KEY=value? Spaces around the equals sign and unmatched quotes cause trouble in some parsers. - Is a shell variable overriding the file? Run
echo "${#LLM_API_KEY}"to see whether one is set. - Do you get a 401 or 403 response? The variable loaded, but the provider rejected the value. Look for a pasted extra character, a revoked key, or a key from the wrong project.
Summary of the pattern
- The code names the variable and never holds the value.
- Local development fills the environment from a git-ignored
.env, and CI and hosting fill it from their own secret settings. - One config module reads, strips, validates, and hides the key.
- The key goes in a header, never in a URL, a log line, or an error message.
Exercise
A teammate's script contains api_key = os.environ.get("LLM_API_KEY", "sk-abc123") and prints print(f"Using key {api_key}") on startup. Name two problems and give the fix for each.
Show answer
The default value puts a real-looking key in source control, and anyone with repository access can read it. Remove the default and raise an error when the variable is missing or empty. The print writes the key into the terminal and any log capture. Remove it and print only whether the key is set, or its length, for example print(f"{len(api_key)} characters set").
Exercise
You edit the value in .env, rerun your Python program, and it still uses the old key. load_dotenv() is called at the top. What is the most likely cause?
Show answer
The old value is already exported in your shell. load_dotenv() does not override existing environment variables by default, so the shell value wins. Unset the variable with unset LLM_API_KEY, or call load_dotenv(override=True) if you want the file to take priority.