How to use a free LLM API in a browser app without exposing your key
Do not put an API key in a Vite browser app, even in an ignored .env.local file. Vite replaces VITE_ variables into client code at build time, so a visitor can read them from the downloaded JavaScript. Keep the key in a server or Worker secret, have the browser call your own authenticated /api/chat route, and let that server make the fixed provider request.
Why .env.local does not hide a Vite key
An ignored file and a private value are different things. .env.local can stay out of Git, yet a variable named VITE_CHINAGENAI_API_KEY is still eligible for Vite's client-side environment replacement. Once the value is part of a JavaScript bundle, the browser has received it. Renaming the variable or minifying the bundle does not restore secrecy.
Treat every value delivered to a browser as public: source code, HTML, JavaScript chunks, source maps, network requests, and browser storage. A frontend cannot safely hold a long-lived provider credential. If a real key has already been built into a deployed asset, remove the exposure and rotate that key; rebuilding only protects future assets.
Use two request hops
Keep the browser request keyless. It sends the user's message to a same-origin endpoint such as /api/chat; it does not send a provider Authorization header.
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
messages: [{ role: 'user', content: 'Explain one short idea.' }],
}),
});
Your server or Worker checks the signed-in user, validates the message list and size, and applies a per-user request limit. It then sends a second request to a fixed API URL using a server-only secret. For ChinaGenAI, the current Chat Completions URL is https://chinagenai.com/v1/chat/completions, and the model label is free; the route chooses its upstream automatically. Check the live connection guide for the current request limits before using a site key.
const upstream = await fetch('https://chinagenai.com/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${env.CHINAGENAI_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'free',
messages: validatedMessages,
max_tokens: 128,
stream: false,
}),
});
This is the forwarding portion of a server handler, not a complete public proxy. Before it runs, require a real user session or an access policy, validate the input, cap the body, and rate-limit the caller. Do not let the browser choose an arbitrary upstream URL or pass through arbitrary headers. Return the upstream status and a safe response body; do not log Authorization headers or prompts.
A same-origin route avoids unnecessary CORS setup, but same-origin is not authentication. CORS controls which cross-origin browser scripts may read a response; it does not prove that a caller is an authorized user. An Origin check can be one filter, but a command-line client can send an Origin header too.
Keep the secret on the server
For a Cloudflare Worker, add CHINAGENAI_API_KEY as a Secret binding and read it as env.CHINAGENAI_API_KEY. Do not put it under plaintext vars, in wrangler.toml, or in any VITE_ variable. For local Worker development, use .dev.vars or .env and ignore those files in Git. Cloudflare documents npx wrangler secret put CHINAGENAI_API_KEY; that command creates and deploys a Worker version immediately, so use it only when a deployment is intended.
If your frontend is deployed as a static site, deploy the server route separately or attach it under the same hostname. Keep the route behind authentication. A public proxy can still spend your key's free allowance even when the key itself never reaches the browser.
Run a bundle canary check
Use a fake marker in a throwaway build, never a real key. For a Vite test copy, temporarily set VITE_CHINAGENAI_API_KEY=BUNDLE_CANARY_NOT_A_REAL_SECRET, reference it from one client module, and run the normal production build. Search the emitted assets and source maps:
Get-ChildItem .\dist -Recurse -File |
Select-String -SimpleMatch 'BUNDLE_CANARY_NOT_A_REAL_SECRET'
A match confirms the scan can detect a client-exposed value. Delete the test build and marker, remove the VITE_ credential, rebuild, and scan again. The real build must contain neither the canary nor a provider key. This canary is a detection exercise, not permission to test with an active credential.
Finish with these three independent checks:
| Check | Safe result | What a failure means |
|---|---|---|
| Built files | No canary or credential value in .js, .map, or HTML assets. |
A build-time variable, source-map entry, or manual define reached the client. Remove it and rotate any real key that was exposed. |
| Browser Network panel | The browser calls only your /api/chat; its request has no provider Authorization header. |
The app is still calling the provider directly, or a client wrapper is attaching the key. |
| Server route | Unauthenticated and over-limit requests stop before the provider fetch; logs omit keys and prompt bodies. | The endpoint can be abused to spend a shared quota, even if the browser bundle is clean. |
Test the route contract against a local mock first if you want to avoid a provider request; the offline client test guide shows that separate workflow. A successful bundle scan alone does not prove that the server endpoint is protected.
Common questions
Does .env.local make the key safe?
No. Git ignore reduces accidental commits. It does not change Vite's rule for variables exposed to client code.
Is an Origin allowlist enough?
No. Browsers attach origins, but non-browser clients can choose their own header values. Use user authentication or a platform access policy, then add origin checks as defense in depth.
What if the app has no user accounts?
Do not publish a shared long-lived key behind an unrestricted endpoint. Either add an access layer, issue narrowly scoped short-lived credentials through a proper authentication flow, or accept that the public route needs strict abuse controls and a small quota. A free API key is still a spendable or exhaustible resource.
Official references
- Vite environment variables and modes — client exposure and build-time replacement; checked 2026-11-09.
- OpenAI API key safety — do not deploy keys in browsers; route requests through a backend; checked 2026-11-09.
- Cloudflare Workers Secrets — secret bindings, local files, and Wrangler behavior; checked 2026-11-09.
- MDN CORS guide — browser enforcement for cross-origin reads; checked 2026-11-09.
- ChinaGenAI connection guide — current endpoint and model label; checked 2026-11-09.