Sub topic 9
Never Put the Key in Browser or Mobile Code
This chapter assumes you can read short Python or JavaScript snippets, know what an HTTP request is, and have already loaded a key from an environment variable. Here you will see why a key must stay on a server, and how to call the LLM provider through your own backend.
Why client code cannot hold a secret
Anything you ship to a browser or phone is readable by the person who runs it. That includes JavaScript bundles, mobile app packages, and config files inside them. Environment variables do not help here. A build tool such as Vite or Next.js can copy a variable into the bundle at build time, and then the key sits in plain text in the downloaded file.
Anyone can also open the browser's network tab and read the Authorization header of your requests. Obfuscation and minification only slow this down. Mobile apps can be unpacked and searched for strings in minutes.
A leaked key lets other people send requests on your account. You pay for their usage, and they can exhaust your rate limits.
The pattern: a backend proxy
Put your own server between the client and the provider. The client talks to your server. Your server adds the key and forwards the request.
The key exists only in the server's environment. The client never sees it, and it never appears in a response.
A minimal proxy
This example uses Python with Flask. It reads the key at startup and exposes one route.
import os
import requests
from flask import Flask, jsonify, request # pip install flask requests
app = Flask(__name__)
API_KEY = os.environ.get("LLM_API_KEY")
if not API_KEY:
raise RuntimeError("LLM_API_KEY is not set")
@app.post("/api/chat")
def chat():
data = request.get_json(silent=True) or {}
prompt = data.get("prompt", "")
if not isinstance(prompt, str) or not prompt.strip() or len(prompt) > 2000:
return jsonify(error="Invalid prompt"), 400
upstream = requests.post(
"https://api.example.com/v1/chat", # placeholder: use your provider's endpoint
headers={"Authorization": f"Bearer {API_KEY}"},
json={"prompt": prompt},
timeout=30,
)
if upstream.status_code != 200:
return jsonify(error="Upstream request failed"), 502
return jsonify(upstream.json())
if __name__ == "__main__":
app.run(port=5000)The browser then calls your route and sends no key:
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt: "Say hello" }),
});
console.log(await res.json());A proxy needs its own protection
A proxy with no checks is an open door. Anyone who finds /api/chat can use your key indirectly. Add these controls:
- Require the user to sign in, and reject anonymous calls.
- Rate limit per user or per IP address.
- Cap the prompt length and the output size you request.
- Fix the model and settings on the server. Do not let the client choose them.
- Return generic errors. Do not forward upstream error bodies or headers, which can reveal request details.
- Set a spend limit on the key, covered in a later chapter.
Common mistakes
| Mistake | Why it fails |
|---|---|
| Calling the provider directly from `fetch` in the browser | The key must be in the page code or the request, so users can read it |
| Putting the key in a `.env` that the bundler inlines | The value is copied into the public bundle |
| Embedding the key in a mobile app and "hiding" it | Strings can be extracted from the app package |
| Logging the full request on the server | The `Authorization` header ends up in log files |
Exercise
A teammate puts the key in VITE_LLM_API_KEY in a .env file, and the React app calls the provider directly. The .env is git-ignored. Is the key safe? What should change?
Show answer
No. Git-ignoring the file only keeps it out of the repository. The VITE_ prefix tells Vite to inline the value into the JavaScript bundle, so every visitor can read it. Move the key to a backend environment variable without that prefix, add a route such as /api/chat that calls the provider, and make the React app call that route. Add authentication and rate limiting to the route, and revoke the exposed key.