Short answer
If your OpenAI or Anthropic key is in browser code, in a VITE_ variable or in the response of an edge function, anyone can copy it from your site and use it on your bill. Hiding it behind a ‘get key’ function doesn’t help, because the browser still receives it. Call the AI provider from an edge function that checks the user and keeps the key in its secrets, then rotate the old key.
Ask an AI about this page:ChatGPTClaude
On this page
An OpenAI or Anthropic API key that reaches the browser is no longer your key: anyone can copy it from your site and send requests that you pay for. That happens when the key sits in frontend code, in a VITE_ variable, or in the response of an edge function that “fetches the key” for the browser. It is rated critical because it needs no account and no skill, the damage is direct money, and the key works for anything your provider account allows. OpenAI’s own advice is blunt: “Never deploy your key in client-side environments like browsers or mobile apps.”
Why it matters
AI builders like to make the first version work as fast as possible, and calling the provider straight from React is the shortest path. Two variants show up again and again.
The key in a Vite variable. Vite’s docs say that variables starting with VITE_ “will be exposed in client-side source code after Vite bundling” and should not contain API keys. The value is pasted into your JavaScript at build time:
const apiKey = import.meta.env.VITE_OPENAI_API_KEY; // shipped to every visitor
export async function suggest(prompt: string) {
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}` },
body: JSON.stringify({ model: "gpt-4o-mini", messages: [{ role: "user", content: prompt }] }),
});
return res.json();
}The key-returning function. A smarter-looking fix moves the key into an edge function secret, then adds a function that returns it so the browser can keep calling the provider directly. The key is still in the browser, just one request later.
Our audit engine found exactly this in our test apps. A travel app had a get-ai-key function that returned OPENAI_API_KEY in its JSON response to any caller: verify_jwt was off for it in supabase/config.jsonc and the handler checked nothing. The browser then called OpenAI directly with that key. The engine rated it critical, pointed to the function and the config file, and noted that the “premium only” check in the UI did not protect anything.
With a leaked key, someone else can run requests on your account until you notice, use up your rate limits so your app stops working, and do anything else that key is allowed to do in your provider account. A spend cap limits the bill, but it doesn’t make the leak harmless.
How to find it in your app
Search the code that ships to the browser and the responses of your functions:
grep -rniE "VITE_[A-Z_]*(OPENAI|ANTHROPIC|CLAUDE|GEMINI)" src .env*
grep -rn "api.openai.com\|api.anthropic.com" src
grep -rln "OPENAI_API_KEY\|ANTHROPIC_API_KEY" supabase/functions | xargs grep -n "Response.json\|JSON.stringify"Any call to api.openai.com or api.anthropic.com from src/ means a key is in the browser. For the third search, read each hit: a function may read the key, but must never put it into a response. Then check your live site: open it, press F12, search all loaded JavaScript (Ctrl+Shift+F in Chrome’s Sources panel) for sk- and watch the network tab for a response that contains a key.
How to fix it
Move the AI call itself to the server. The edge function checks the user, reads the key from its secrets and returns only the answer:
import { withSupabase } from "npm:@supabase/server@1";
const MAX_PROMPT_CHARS = 2_000;
export default {
fetch: withSupabase({ auth: "user" }, async (req) => {
const body = await req.json().catch(() => null);
const prompt = typeof body?.prompt === "string" ? body.prompt.slice(0, MAX_PROMPT_CHARS) : "";
if (!prompt) return Response.json({ error: "Missing prompt" }, { status: 400 });
// The key stays in the function's secrets; the browser never sees it.
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
},
body: JSON.stringify({
model: "gpt-4o-mini",
max_completion_tokens: 500,
messages: [{ role: "user", content: prompt }],
}),
});
if (!res.ok) return Response.json({ error: "AI request failed" }, { status: 502 });
const data = await res.json();
return Response.json({ text: data.choices?.[0]?.message?.content ?? "" });
}),
};The browser calls your function, not the provider. supabase.functions.invoke sends the signed-in user’s token along:
import { supabase } from "@/integrations/supabase/client";
export async function suggest(prompt: string): Promise<string> {
const { data, error } = await supabase.functions.invoke("ai-suggest", { body: { prompt } });
if (error) throw new Error("The suggestion could not be created");
return data.text as string;
}Store the key with Edge Functions → Secrets in the dashboard or supabase secrets set; Supabase’s docs also remind you to keep supabase/functions/.env out of git. The model and the token limit are fixed on the server, so nobody can switch to an expensive model through your function. Then rotate the key in your provider dashboard and delete the old one, and remove VITE_OPENAI_API_KEY and the key-returning function.
Remove every AI provider API key from browser code: delete any VITE_ variable that holds an OpenAI, Anthropic or other AI key, and delete any edge function that returns a key in its response. Create a Supabase edge function that requires a signed-in user (withSupabase with auth: “user” from npm:@supabase/server), reads the key with Deno.env.get from the function secrets, calls the provider with a fixed model and a fixed output token limit, and returns only the generated text. Change the frontend to call this function with supabase.functions.invoke instead of calling the provider directly.
Do not log the key or put it in any response. Afterwards, list every file that still references an AI provider URL or key name, and remind me to rotate the old key in the provider dashboard.
Check that the fix works
- Build the app and search the output:
grep -rn "sk-\|api.openai.com\|api.anthropic.com" dist/must find nothing. - Open your live site with the network tab, use the AI feature and confirm that requests go only to your Supabase project, and that no response contains a key.
- Call the function without signing in; it must answer 401.
- In the provider dashboard, the old key must show as revoked, and usage must only come from the new one.
The guide to API keys in the frontend explains which keys are public by design and which are not. Next, put a ceiling on what the function may spend: no AI spend cap.
Frequently asked questions
My key is only in a .env file. Is that safe?
Only if the variable has no VITE_ prefix and is never imported in browser code. Vite’s docs say VITE_ variables are bundled into the client code at build time, so a VITE_OPENAI_API_KEY ends up in the JavaScript every visitor downloads.
The function that returns the key requires a login. Isn’t that enough?
No. Every signed-in user receives the key and can keep using it outside your app, without your limits, until you rotate it. In most apps anyone can create an account. The key must never leave the server.
I removed the key from the code. Am I done?
No. Rotate it in the provider’s dashboard. Old builds, browser caches, git history and anyone who already copied it still have the old key; only revoking it makes it useless.
Is the Supabase publishable or anon key in the same category?
No. That key is meant for the browser and its reach is limited by your RLS policies. AI provider keys, the Stripe secret key and the Supabase secret or service_role key are server-only.
Sources
- 1.Best practices for API key safety — OpenAI Help Center
- 2.Env Variables and Modes — Vite
- 3.Environment variables — Supabase Docs
- 4.Securing Edge Functions — Supabase Docs
- 5.CWE-798: Use of Hard-coded Credentials — MITRE
- 6.CWE-200: Exposure of Sensitive Information to an Unauthorized Actor — MITRE