Sub topic 9
Never put the key in browser or mobile code
This chapter assumes you can read short JavaScript and Python snippets, know what an HTTP API is, and have already loaded a key from an environment variable. Here you will see why the key must stay on a server you control, and how to build the small backend that makes that possible.
Why client code cannot keep a secret
Code that runs on a user's device is controlled by that user. A browser, a phone, and a desktop app all hand the user everything the program contains and every request it sends.
- Browser JavaScript is delivered as readable text. Anyone can open the developer tools, view the source, or watch the Network tab and see the
Authorizationheader on each request. - Mobile apps are packaged files that can be unpacked. Strings embedded in the binary can be extracted with common tools. Traffic can be inspected with a proxy that the user installs on their own device.
- Obfuscation and encryption only add steps. The app must decrypt the key before it can send it, so the decrypted key is always present at runtime.
Environment variables do not change this. A bundler may inject process.env.LLM_API_KEY into your frontend build, but the value is then copied into the shipped JavaScript file as plain text.
What an attacker can do with a stolen key
The key authorizes requests on your account. Whoever holds it can:
- Send their own prompts, and you pay for the tokens.
- Burn through your rate limits so your real users get errors.
- Use your account for content that breaks the provider's terms, which can get your account suspended.
- Run the key at high volume until a spend limit stops it, or until your balance is gone.
Automated scrapers look for keys in public repositories and websites. A key in a public bundle may be found and abused within hours.
The standard fix: a backend proxy
The solution is to put your own server between the client and the provider. The client talks to your backend. Your backend holds the key, adds it to the request, and forwards the call.
The key exists only in the backend's environment. The browser never receives it, not even in an error message.
A minimal backend proxy
The following Flask server reads the key from the environment, accepts a prompt from the client, and forwards it. The provider URL is a placeholder. Use your provider's documented endpoint and request format.
import os
import requests
from flask import Flask, jsonify, request
app = Flask(__name__)
API_KEY = os.environ.get("LLM_API_KEY")
if not API_KEY:
raise RuntimeError("LLM_API_KEY is not set")
MAX_PROMPT_CHARS = 2000
@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():
return jsonify(error="prompt must be a non-empty string"), 400
if len(prompt) > MAX_PROMPT_CHARS:
return jsonify(error="prompt is too long"), 400
try:
upstream = requests.post(
"https://api.example.com/v1/chat", # placeholder URL
headers={"Authorization": f"Bearer {API_KEY}"},
json={"prompt": prompt},
timeout=30,
)
except requests.RequestException:
return jsonify(error="upstream request failed"), 502
if upstream.status_code != 200:
# Do not forward the provider's raw response or headers.
return jsonify(error="upstream error", status=upstream.status_code), 502
return jsonify(answer=upstream.json())
if __name__ == "__main__":
app.run(port=5000)Points worth noting in this code:
- The key is read once at startup, and the server refuses to start without it.
- The client controls only the
promptfield. It cannot choose the URL, the headers, or other model settings. - The prompt is validated for type and length before anything is sent.
- Error responses carry no provider headers, request details, or key.
Calling your backend from the browser
The frontend code now contains no secret. It sends a request to your own route:
async function ask(prompt) {
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt }),
});
if (!response.ok) {
throw new Error(`Request failed with status ${response.status}`);
}
return response.json();
}A mobile app does the same thing: it calls https://your-domain.example/api/chat, never the provider directly.
A proxy alone is not enough
A proxy moves the key off the client, but it does not protect your account. If /api/chat is open to everyone, an attacker can skip your frontend and call it directly, which spends your money just as a stolen key would. The backend must decide who may call it and how much.
| Control | What it prevents | Where it runs |
|---|---|---|
| Authentication (login, session, signed token) | Anonymous strangers using your endpoint | Your backend |
| Per-user rate limits | One user or script sending thousands of calls | Your backend |
| Input size limits | Very long prompts that cost a lot of tokens | Your backend |
| Fixed model and settings | Clients choosing the most expensive model | Your backend |
| Provider spend limit | Total loss if every other control fails | Provider console |
| CORS policy | Other websites calling your API from a user's browser | Your backend |
Note that CORS (Cross-Origin Resource Sharing) is enforced by browsers. It does not stop scripts, curl, or other servers. Treat it as a defense against other websites, not as access control.
Edge cases and common mistakes
Keys in the bundle by accident
A build tool can include a key you never meant to ship. For example, a .env file read by a frontend build may be copied into the bundle. After building, search the output for your key prefix:
npm run build
grep -r "sk-" dist/ || echo "no matches"Replace sk- with the prefix your provider uses, and adjust dist/ to your output folder. Do this only with a prefix, not the full key, so the key does not end up in your shell history.
Keys in source maps and mobile builds
Source maps can reveal original source files. If a key was ever in the source, a published map file exposes it. For mobile apps, check that build config files and plist or XML resources do not contain the key. Release builds are not a safe place either.
Direct-from-client keys that the provider designs for it
Some providers offer short-lived tokens or restricted client keys meant for browsers, for example for realtime voice features. These work differently from your main API key: your backend creates a token with a short expiry and narrow permissions, and the client uses only that token. Check your provider's documentation. If the provider does not describe such a mechanism, assume it does not exist and use the proxy.
Streaming responses
If you stream tokens to the client, the proxy must stream them too. The key still never leaves the backend. Make sure that streaming errors are cleaned the same way as normal errors, so a failed stream does not print request headers into the response.
Logging
Do not log request headers in your proxy. A debug line that prints headers writes the key into your log files. Log the status code, a request ID, and the user ID instead.
Local testing
A key in a demo page "just for testing" tends to be shared and committed. Use the backend even for prototypes. The Flask example above runs locally in a few seconds.
Checklist
- The key is read only on the server, from an environment variable.
- No frontend variable prefix exposes it.
- Clients call your own route, not the provider.
- The route requires authentication and enforces rate and size limits.
- Model and token settings are fixed on the server.
- Errors and logs contain no headers or key.
- A spend limit is set at the provider.
Exercise
A teammate says the key is safe in the mobile app because the app code is compiled and the key is split into three strings joined at runtime. Why is that wrong, and what should the app do instead?
Show answer
The app must join the strings to send the request, so the full key exists in memory and in network traffic, where the user can capture it with a proxy or a debugger. Compiling only slows extraction. The app should call your own backend, which holds the key, authenticates the user, applies rate and size limits, and forwards the request to the provider.
Exercise
You built a proxy at /api/chat that adds the key server-side, but it accepts requests from anyone and passes through the client's "model" and "max_tokens" fields. Name two ways an attacker can still cost you money, and one fix for each.
Show answer
First, the attacker can call /api/chat directly in a loop, since no authentication or rate limit exists. Fix: require login and apply per-user rate limits. Second, the attacker can choose the most expensive model and a huge max_tokens value. Fix: set the model and token limits on the server and ignore those fields from the client. A provider spend limit is a further safety net.