Sub topic 2
Using a `.env` File for Local Development
Assume you know basic command-line commands, Git, and short Python or JavaScript snippets. An environment variable is a named value supplied outside your source code. Use one for an LLM API key so the key does not become part of your project files.
Using a `.env` File for Local Development
A .env file is a local text file containing KEY=value entries. It is convenient for development, but it is still a secret. Create it in your project directory:
# .env
LLM_API_KEY=paste-your-key-hereKeep the file on your machine. Do not upload it, email it, or include its contents in screenshots.
Keeping `.env` Out of Git
Git tracks files that you commit. Add .env to .gitignore before committing:
echo ".env" >> .gitignore
git check-ignore -v .envThe second command should show the .gitignore rule that excludes the file. Commit a safe template such as .env.example instead, using an empty or clearly fake value.
Reading the Key in Your Code
Load the file at application startup and read the key from the environment. This Python example uses python-dotenv:
import os
from dotenv import load_dotenv # pip install python-dotenv
load_dotenv()
api_key = os.environ.get("LLM_API_KEY")
if not api_key:
raise RuntimeError("LLM_API_KEY is not set")Real environment variables take precedence by default. This lets a deployment system provide the production key without changing the code.
Checking the Setup Safely
Verify presence without printing the key:
print(f"{len(api_key)} characters set")Do not log the key, request headers, full environment, or exception data that might contain the key.
Never Put the Key in Browser or Mobile Code
Browser and mobile code runs on a user’s device. Users can inspect its source, network requests, or installed files. Put the key on your server instead. The client calls your backend, and the backend calls the LLM provider.
Use separate keys with limited permissions and spending limits when your provider supports them. Store deployment keys in the CI or hosting platform’s secret settings. For larger systems, use a dedicated secret manager.
Exercise
Why is a .env file safer than putting the key directly in Python code, and what protection is still required?
Show answer
It separates the key from source code, but you must still keep .env out of Git, protect the machine, and revoke the key if it leaks.