AI APIs & Structured Outputs· Lesson 6 of 7
- 1The First Call — Reaching the Model From Code7 min
- 2Streaming — The Reply Arrives Word by Word7 min
- 3Structured Outputs — JSON You Can Rely On8 min
- 4Errors & Retries — When the Call Fails9 min
- 5Rate Limits — Your Ceiling per Minute6 min
- 6API Keys & Secrets — Guarding Your Key6 min
- 7Timeouts & Idempotency — Requests That Don't Double-Fire8 min
API Keys & Secrets — Guarding Your Key
In one line · An API key is the password that proves it's you, and anyone who gets it can spend from your account — so it lives in environment variables, never in code.
One key leaked to GitHub can cost you a fortune in hours. Protecting secrets isn't a luxury — it's the first lesson in securing any real app.
Like your house key: you don't tape it to the front door. You keep it somewhere safe (an env var / secrets manager) and the code reads it at runtime only — it never appears in the repo.
A key is like a hotel keycard: it opens your room, and anyone who finds it walks in and runs up your bill. That's why the front desk can deactivate it in a second and print you a new one — exactly how you revoke a leaked key and issue a replacement.
Instead of writing the key in code, you put it in a .env file (and add it to .gitignore) and read it from process.env — and in production from a secrets manager; if it ever leaks, you revoke it and issue a new one at once.
The provider issues a key per account or project, and you send it in the Authorization header with every call. Locally it lives in a .env file added to .gitignore; in production, in a secrets manager or the platform's env vars — code reads it at runtime only. If it leaks, you revoke immediately and issue a replacement. Best practice gives each environment and each app its own key with the least privilege possible — so a leaked key has a small, traceable blast radius.
🧪 Try it yourself: take a script with a hardcoded key and move it to a .env file added to .gitignore, reading it from process.env. Make the app fail with a clear message when the key is missing — instead of sending a request with an undefined key and getting a cryptic 401.
(1) Committing the .env file or hardcoding the key — bots scan GitHub and find keys within minutes. (2) Putting the key in frontend code — anyone opening DevTools copies it and spends from your account. (3) One shared key for all environments with no rotation — if it leaks you can't tell from where, and revoking it takes everything down at once.
From the very first line of code: an env var locally, a secrets manager in production, and a separate key per environment (dev/staging/prod) from the start — building the habit beats fixing the leak.
The key never appears in: the repo, frontend code, logs, chat messages, or any third-party service that doesn't need it. And if you're unsure whether it leaked — assume it did and revoke.