Protecting model credentials in mobile and web projects

Anyone shipping an AI feature in a phone app or a single-page site eventually hits the same worry: the model needs a key, and anything shipped to a user's device can be read by that user. Developers preparing their first store release often hear stories about surprise invoices and stolen credentials and want to know what actually protects them.
This guide walks through the threat in plain terms, then gives a step-by-step setup that keeps the secret on a server you control, limits what a stolen key could do, and puts a ceiling on spending. It also explains where a keyless endpoint removes the problem entirely and where it does not.
Frequently asked questions
Is it safe to put a Gemini API key directly in a mobile app?
No. App bundles can be unpacked and network traffic can be inspected, so any key inside the app should be treated as public. Obfuscation slows down a casual attacker but does not stop a determined one.
What is a backend proxy in this context?
A small server or serverless function that holds the real key. Your app talks to the proxy, the proxy checks who is calling and what they ask for, then forwards the request to the model provider. The key never leaves the server.
Why are older Google API keys suddenly a concern?
Google Cloud keys were historically created for services such as Maps and were often embedded in client code because those services were considered low risk. Security researchers have warned that if the Gemini API is enabled on the same project, such a key may also be usable for model calls. Review which APIs each key can reach.
How do API key restrictions differ from a proxy?
Restrictions limit where a key works, such as which APIs, apps or referrers it accepts. They reduce damage but rely on information a client can sometimes fake. A proxy keeps the key secret in the first place. Use restrictions as an extra layer, not the only one.
Can billing alerts stop a runaway bill?
Budget alerts notify you, they do not automatically block spending unless you build that action. Combine alerts with quotas or a kill switch in your proxy so that abuse is contained, not just reported.
Can shared or leaked keys help me avoid paying?
No. Using someone else's key is unauthorised use of their account, the keys get revoked quickly, and anything you send passes through an account you do not control. Never build on borrowed credentials.
Does a keyless endpoint remove the key problem?
For this site's free-ai model, yes, because there is no key to steal. The trade-off is that limits apply per IP, there is no SLA, and the model is an independent open-weight model, not Gemini. It suits prototypes and low-stakes features better than paid production traffic.
What should I log in my proxy?
Log user or device identifiers, timestamps, model, token counts and status codes. Avoid logging full prompts with personal data unless you need them and have told users. Token counts per user are what reveal abuse early.
Step by step
- Inventory your keys — List every API key in every cloud project and note which APIs each one can call.
- Restrict or delete old client keys — Limit maps and other client-side keys to their single intended API, and delete keys nobody uses.
- Create a server-only model key — Make a new key just for model calls, store it in your server's secret manager, and never ship it in an app.
- Put a proxy in front — Route app requests through a small authenticated endpoint that enforces per-user limits and forwards to the provider.
- Add alerts and a kill switch — Configure billing alerts and a feature flag that stops model calls without a new release.
- Scan and rotate — Enable secret scanning in your repositories and rotate the server key on a schedule and after any suspected leak.
The threat model in one paragraph
Assume every byte you ship to a client is readable. Someone can decompile an app, open the developer tools in a browser, or route a phone through an intercepting proxy and see every request. If a provider key is in that traffic, it can be copied and used from anywhere until you revoke it, and every request is billed to you.
That is why the advice from experienced developers is consistent: the key lives on a server, and the app gets a short-lived, narrowly scoped way to ask that server for help. Everything else in this guide is a refinement of that one rule.
Why obfuscation is not protection
Splitting a key into pieces, encoding it or hiding it in native code raises the effort required, but the app must reconstruct the key to use it, and so can an attacker. Treat obfuscation as a speed bump only.
The cost of one leak
A stolen model key can be used for bulk generation that has nothing to do with your product. Even with free-tier limits, a key attached to a billing account can rack up charges until someone notices.
Old keys, new permissions
A less obvious risk comes from keys created years ago. Many projects have API keys made for maps, places or other client-side services, and those were routinely pasted into web pages. Security reporting has highlighted that if the generative language API is later enabled in the same Google Cloud project, a supposedly harmless key may gain access it never had before.
The fix is housekeeping. List every key in each project, check which APIs it is allowed to call, and restrict each key to the single API it was made for. Create a dedicated, server-only key for Gemini and never reuse a client-side key for it.
Quota and billing behaviour also differ between account sign-in and API keys, which is covered in the guide to Gemini quotas.
Separate projects for separate risk
Putting the model workload in its own cloud project gives it its own keys, quotas and billing alerts. A mistake in a maps key then cannot reach the model at all.

A minimal backend proxy
The proxy does not need to be large. Its job is to authenticate your user, apply your own per-user limits, optionally rewrite or check the prompt, and forward the call. A serverless function on any common platform is enough for most apps.
Below is a compact example using Flask. It reads the provider key from an environment variable, enforces a naive per-user daily counter, and forwards to an OpenAI-compatible endpoint. Swap the base URL and model for whatever provider you use; the shape stays the same.
Keep the proxy boring. It should do authentication, limits, logging and forwarding, nothing clever. Every extra feature is another place for bugs, and the proxy sits on the path of every AI request your app makes.
Authenticate before you forward
Use the identity system you already have, such as a session token or a signed device token from your auth provider. Anonymous proxies simply move the open door from the provider to your server.
Enforce your own limits
Cap requests and tokens per user per day in the proxy. Provider limits protect the provider; your limits protect your budget and your fair-use promises.
import os
from collections import defaultdict
from flask import Flask, request, jsonify, abort
from openai import OpenAI
app = Flask(__name__)
client = OpenAI(base_url=os.environ["MODEL_BASE_URL"], api_key=os.environ["MODEL_API_KEY"])
MODEL = os.environ.get("MODEL_NAME", "free-ai")
used = defaultdict(int) # use a real store such as Redis in production
DAILY_LIMIT = 200
def current_user():
token = request.headers.get("Authorization", "").removeprefix("Bearer ")
if not token: # replace with real token verification
abort(401)
return token
@app.post("/ai")
def ai():
user = current_user()
if used[user] >= DAILY_LIMIT:
abort(429)
used[user] += 1
text = (request.get_json(silent=True) or {}).get("text", "")[:4000]
r = client.chat.completions.create(
model=MODEL,
max_tokens=500,
messages=[{"role": "user", "content": text}],
)
return jsonify(answer=r.choices[0].message.content)
Restrictions and quotas on the provider side
Even with a proxy, restrict the server key. In Google Cloud you can limit a key to specific APIs and, for server use, to specific IP addresses. Set quotas lower than the default so that a bug in a loop cannot consume a month of budget in an hour.
Check Google's current documentation for which restriction types apply to generative model keys, since options differ between AI Studio keys and full Vertex AI credentials and can change. When in doubt, the stricter configuration is the right default.
Rotate on a schedule
Rotate the server key periodically and immediately after any suspected exposure, such as a key accidentally committed to a repository. Keep the rotation procedure written down so it takes minutes, not an afternoon.
Scan your repositories
Secret scanning in your code host and a pre-commit hook catch most accidental commits. A key that never reaches the repository is a key you never have to rotate in a panic.

Budget alerts and a kill switch
Cloud billing can send alerts at thresholds you choose, for example half and all of your monthly budget. Alerts arrive after spending happens, so pair them with something that acts. Your proxy can read a feature flag and refuse AI calls when the flag is off, giving you a one-click stop while you investigate.
Image generation and other premium endpoints deserve extra care. Developers setting up paid image models often struggle first with payment configuration and then with understanding how quickly per-image charges add up. Put those endpoints behind their own, lower per-user caps.
Per-user caps on premium features
Give every user a daily allowance for expensive operations such as image generation, and show the remaining allowance in the interface. Honest users rarely notice the cap, while a script abusing a stolen session hits it within minutes.
- Alert at 50%, 90% and 100% of the monthly budget
- Keep a feature flag that disables model calls without a new release
- Track tokens per user per day and flag outliers
- Give expensive endpoints their own stricter limits
When the client must call the model directly
Some apps have no backend at all, for example a hobby browser extension or a quick internal tool. In those cases, a few safer options exist. Some platforms offer client SDKs that combine app attestation with server-side key handling, so the key stays with the platform rather than in your code. Check whether your platform provides something like that for Gemini and read its current documentation.
Another option is a keyless endpoint for features where an open-weight model is good enough. With no secret involved, there is nothing to leak, although per-IP limits mean every user shares the same rules.
Browser calls and CORS
The endpoint on this site has CORS open, so a static page can call it with fetch and no key. That is convenient for demos and personal tools, and it is also why it is not a substitute for an authenticated proxy when you need per-user accounting.
Rate limit the proxy itself
Even an authenticated proxy should limit requests per user and per IP. Credential stuffing and compromised accounts are common, and a rate limit turns a potential bill into a handful of rejected requests.

What a keyless endpoint changes, and what it does not
APIFreeGemini is an independent service and is not affiliated with Google. Its free-ai model is an open-weight model of about 35B parameters, reached at https://api.apifreegemini.com/v1 with any placeholder key. Because there is no account, there is no credential to protect and no invoice to fear.
That does not make it a drop-in Gemini replacement. Limits are per IP: one request per second with short bursts, two in parallel, and a daily budget. There is no SLA and no image or audio input. Every request leaves a technical log with time, IP, User-Agent and token counts, so do not send secrets through it. It is a good fit for prototypes, internal tools and backup routes, as described in the guide to automation without keys.
Keep the fallback honest
If you use a keyless endpoint as a cheaper or backup route, tell users which features may answer differently. The model is not Gemini, so answers will vary in style and quality, and that is better explained than discovered.
Send a test prompt to the keyless free-ai endpoint from the home page, no sign-up or key required.
Read also
- Why do non-English prompts burn more tokens on Gemini and others?
- Why did a Gemini model vanish from my picker, and what should I do?
- Are real-time Gemini voice agents ready for production calls?
- Should you build on Gemini Flash or Flash-Lite for your app?
- Gemini CLI vs Antigravity vs OpenCode: which terminal agent fits?