Keys
🏠The everyday picture
A company credit card with no limit, handed to a stranger, is a disaster. API keys are exactly that: anyone holding yours can spend your money.
📘What it really is
- An API key identifies your account and is billed for every request made with it.
- Rules for AI keys (they're secrets, Module 77):
- never in frontend code or mobile apps; anyone can read them there and run up your bill. The browser calls your backend; your backend calls the AI API (Module 81's diagram);
- never in Git; keep them in
.envlocally (ignored) and in secrets on servers and CI; - a separate key per environment (development, staging, production) and per app, so one leak doesn't affect the rest, and costs are easy to see;
- spending limits and alerts on the provider account;
-
revoke and replace immediately if one leaks (Module 77).
-
Your backend becomes the gatekeeper:
- only logged-in users may use the assistant (Module 74);
- rate-limit per user (Module 76), since each request costs money;
- limit input size (long pastes cost more) and
max_tokens; -
log usage per user for cost tracking (Lesson 4), without logging sensitive content unnecessarily (Module 89).
-
Data terms: read how the provider handles what you send: whether it's stored, for how long, whether it's used for training, and where it's processed. Business API terms usually differ from consumer chat apps. Don't send restricted data (Module 79) without checking.
🖱️Try it
Create an Express route POST /v1/assistant/ask in your backend that requires login, accepts { question } (validated with
Zod: a string of at most 2,000 characters), calls the model with your system prompt, and returns the answer. Add a per-user rate
limit (for example, 20 a minute). Confirm the key exists only in your backend's environment, and that the frontend has no trace
of it.
✅Quick check
Why must the browser never call the AI API directly with your key?
Show the answer
Anyone could read the key from the frontend and use it at your expense.
Why rate-limit the assistant route per user?
Show the answer
Every request costs money, and one user (or attacker) could otherwise run up a large bill.
