Everything in a web build is public, so the model key lives on a small server you control, every call has a timeout and a fallback, and each player has a budget. That holds for AI in browser games of every kind, from a talking character to a hint button, in JavaScript games and Unity Web builds alike, because the request leaves from a browser the player controls.
This guide covers features that call a hosted large language model (LLM) during play. Keeping game rules out of the model has a separate guide on this blog, Add an LLM NPC to Your Game Without Handing It the Rules.
/01
Why does an API key in a WebGL build leak?
A web game is a set of files that the browser downloads and runs. Unity's manual lists the contents of a Unity Web build: a loader script, a framework file with the JavaScript runtime, a WebAssembly binary and a data file holding asset data and scenes. A key in a C# script, a ScriptableObject or a bundled config file ships with the build to the player's machine. Fetching the key at startup does not help, because the browser's developer tools show every response.
Google's Gemini API documentation says keys compiled into client-side code can be extracted by users, and that client-side apps should run a backend proxy server to make the actual API calls. Whoever holds the key can run up your bill; OWASP's Top 10 for LLM applications calls attacks on that cost-per-use model Denial of Wallet. Anthropic's key guidance adds separate keys per environment, spend limits as a safeguard against leaked keys, and immediate revocation of a key that may be compromised.
/02
What does a minimal model proxy need to do?
The proxy is a small endpoint you own: it receives the player's input and some game context, builds the prompt, calls the provider, checks the answer and returns something the game can use. Keep the key in an environment variable or encrypted secret storage, as Anthropic suggests, and keep the system prompt, model name and output length on the server, where a modified client cannot change them.
An origin allowlist is not authentication: MDN describes CORS as a server telling browsers which other origins may load its resources, and a script calling your proxy directly never asks.
Player text can also try to rewrite your instructions, which OWASP calls prompt injection. The defense is structural: the model proposes, the server validates against a fixed list of actions, and game code decides, as that separate NPC guide describes.
Providers will not limit individual players for you. OpenAI's rate-limit guide says its limits apply at the organization and project level, not the user level, and recommends per-user usage limits with a hard cap or manual review. So the proxy should:
- Issue a short-lived token per play session, valid only at the proxy; the player can read it, so it must be worthless elsewhere.
- Rate-limit each token and network address and cap input size, both listed among OWASP's mitigations for unbounded consumption.
- Keep a daily budget per player, counted in provider-reported tokens, and stop calling the model once it is spent.
- Validate output before the game sees it; OWASP advises treating the model as any other user, with zero trust, and encoding output for where it is shown.
- Set a spend limit with the provider too, which OpenAI and Anthropic both document, so a bug in your budget code still has a ceiling.
/03
How do you keep model latency out of the game loop?
A model reply can take many frames, so the frame loop must never wait for one. Start the request, show a thinking state, keep simulating and rendering, and when the reply arrives, check that it still belongs to the current conversation.
Give every call a timeout. MDN documents that AbortController can abort a fetch and the reading of its body, and that an aborted fetch rejects with an AbortError. AbortSignal.timeout() is shorter, but its timer cannot be canceled and pauses while the page is in the back-forward cache; when you want to cancel the timer early, MDN suggests AbortController with setTimeout() instead, calling clearTimeout() when the operation finishes, as in the example.
MDN also notes that fetch() fulfills rather than rejects on an error status, so a budget-spent reply arrives as an ordinary response. The example falls back on anything but a well-formed success and displays model text as plain text, never HTML.
// Ask our own proxy for an NPC line. The page never talks to the model provider.
async function askNpc(playerText, { sessionToken, timeoutMs, fallbackLine }) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch('/api/npc-line', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${sessionToken}`
},
body: JSON.stringify({ text: playerText }),
signal: controller.signal
});
if (!response.ok) return fallbackLine; // budget spent, rejected output, server error
const data = await response.json();
return typeof data.line === 'string' ? data.line : fallbackLine;
} catch (error) {
return fallbackLine; // AbortError after the timeout, or a network failure
} finally {
clearTimeout(timer);
}
}
// The frame loop never awaits this call; the dialogue shows a thinking state meanwhile.
const conversationId = dialogue.open(npc.id);
askNpc(playerInput, { sessionToken, timeoutMs: config.aiTimeoutMs, fallbackLine: npc.cannedLine })
.then((line) => {
if (dialogue.currentId === conversationId) dialogue.showText(line); // plain text, not HTML
});/04
Stream the words, validate the actions
Streaming shortens the wait a player feels. OpenAI's production guide says it makes the model start returning tokens as soon as they are available, and MDN notes that a fetch response body can be read incrementally as it arrives. Stream only words meant for display. Anything the game acts on, such as an item or a quest change, must wait until the full output passes server validation.
OpenAI also notes that requests with a lower max_tokens setting incur less latency. Anthropic's streaming documentation warns that errors, such as an overloaded error, can arrive inside the event stream, so decide whether a line that stops halfway stays or gives way to the fallback.
/05
Keep the game playable when the model fails
Assume the feature will sometimes fail: a busy provider, a dropped connection, a spent budget, rejected output or the feature switched off. OWASP recommends designing systems to degrade gracefully, keeping partial functionality rather than failing completely.
Retry carefully. Anthropic's rate-limit documentation says an exceeded limit returns a 429 error, sometimes with a retry-after header giving the wait; at the monthly spend cap there is no such header and retries fail until access resumes. Retry once, on the server, and only when the provider says when; otherwise send the fallback. When every client retries by itself, an outage becomes a traffic spike.
Keep quests, inventory and saves in game code, so a failed reply costs a line of dialogue, not progress. Add a server-side switch for each AI feature and run your release checks with it off. Write the fallback first; four patterns to start from:
- Designer-written lines for each character and situation, chosen by game state.
- The non-AI version of the feature, such as a fixed hint sequence.
- Cached replies for requests without player text, keyed by game state.
- A short in-world message when the player's budget is spent.
/06
Treat player text as personal data
Players type names and other personal details into free-text boxes, and every request carries an IP address. The European Commission defines personal data as any information relating to an identified or identifiable living individual, and gives a name, an IP address and a cookie ID as examples. Treat player text as personal data that your proxy forwards to a third party, the model provider.
The Commission's summary of the GDPR principles says to collect and process only the personal data necessary for the purpose, store it for the shortest time possible and inform the people concerned. Say in your privacy policy that typed text goes to a named provider, what you keep and for how long, and read the provider's own retention terms. This is not legal advice; check the rules where you operate.
OWASP's Logging Cheat Sheet lists access tokens, session identification values and sensitive personal data among things to remove, mask, hash or encrypt rather than log directly. Log call metadata by default, not raw text, and keep any review samples separate, disclosed and short-lived.
/07
Measure cost per session and quality per call
Have the proxy, not the client, record one event per model call. Anthropic's streaming events include a usage field with cumulative token counts, and OpenAI's production guide says to consider cost as a function of the number of tokens and the cost per token. Multiply by the provider's current published prices, note the date you read them, and sum by session.
Review cost per session as a spread, not an average. Outliers can mean a loop in your code, a client calling too often or someone probing your budget, and OWASP recommends monitoring for unusual patterns of consumption. For quality, count fallbacks, rejected outputs and what players do next, and watch frame time while the feature runs. Each event holds:
- A pseudonymous session ID, the feature, the model and the provider-reported input and output tokens.
- Time to first token and total time, measured on the proxy.
- The outcome (success, timeout, provider error, rejected, budget spent or switched off) and whether the player saw the fallback.
/08
What one portal's requirements say about data and origins
Portal rules differ; read each portal's own documentation. CrazyGames' technical requirements, for example, say a game collecting personal data beyond the events in its SDK should show new players a Terms & Conditions and/or Privacy Policy notice, and recommend a simple notice rather than a pop-up that blocks play.
The same page's sitelock section notes that CrazyGames runs on several crazygames.com origins, and that its iOS and Android apps have their own origins. If your proxy accepts requests only from known origins, list all of them.
/09
Where AI Games Kit fits, and where it does not
AI Games Kit has no model proxy, in-game LLM component or hosted AI service. For the work around such a feature, its Web Game Developer agent implements browser-game code, its Game Remote Config & Analytics Engineer agent handles kill switches and analytics events, and its Browser Game Performance Audit, Web Portal Readiness Check and Game Release Regression Check skills cover latency, portal builds and release candidates.
Keep this in mind
Key takeaways
- Treat any key that reaches the browser as published; keep the provider key on your server.
- Let the proxy own the prompt, model, output length, per-player budget and output validation.
- Never make the frame loop wait: time out each call, check response.ok, stream only display text.
- Write a fallback for every AI moment and keep quests, inventory and saves in game code.
- Disclose that player text goes to a model provider, and log metadata rather than raw text.
- Record tokens, latency and outcome per call on the server; review cost per session as a spread.
Sources & further reading
Consult the source documentation for the version and platform you are working with.
- Google AI Studio: Using Gemini API keys
- Unity Manual: Web Build folder
- Claude Help Center: API key best practices
- OWASP GenAI: LLM10:2025 Unbounded Consumption
- OWASP GenAI: LLM05:2025 Improper Output Handling
- OWASP GenAI: LLM01:2025 Prompt Injection
- OpenAI API: Rate limits
- OpenAI API: Production best practices
- Claude API: Rate limits
- Claude API: Streaming messages
- MDN: Cross-Origin Resource Sharing (CORS)
- MDN: AbortController
- MDN: AbortSignal.timeout()
- MDN: Using the Fetch API
- European Commission: Data protection explained
- European Commission: Principles of the GDPR
- OWASP Logging Cheat Sheet
- CrazyGames: Technical requirements