If your API key leaked, revoke it first and investigate second. Create a new key, delete the old one in the provider’s dashboard, set a hard spending limit, and check the usage page to see what was charged. Then find out how it got out. In AI-built apps, the most common reason is that the key sits in the code your app sends to every visitor’s browser or phone.
That last part is why this keeps happening. Lovable, Bolt.new, v0, Rork and Cursor are all happy to call OpenAI, Claude or Gemini straight from the frontend, because it works on the first try. It also hands your key, and your credit card, to anyone who opens developer tools. This guide covers what to do in the first hour, how to check whether a key is exposed, how to ask for a refund, and how to move the key somewhere it can’t be copied, with working code.
Why leaked AI keys are a bigger problem right now
An AI provider’s API key works like a password tied to your billing account. Whoever holds it can run models, and you pay.
Stolen AI keys have become a business. In its incident report published on 10 November 2026, hosting platform Railway said attackers who got in on 20-21 October went specifically after AI provider keys stored by its customers, and ran up an estimated $740,000 in usage on them. Railway names OpenCode, Warp and Fireworks AI among other companies that disclosed similar thefts in October, and a breach at Fireworks AI led to attackers reaching Cursor’s internal systems, including stored AI chat history that contained credentials. Security people call this LLMjacking: stealing keys and reselling access to the models.
You don’t need a platform breach to lose a key, though. A scan of 978 public apps built with tools like Lovable, Bolt and v0 found 37 of them sending at least one secret key to every visitor, including keys for OpenAI, Gemini, Groq and OpenRouter. Bots scan for exactly this.
What to do in the first hour after an API key leak
Do these in order. The first two stop the bleeding. The rest can wait until the key is dead.
- Revoke the leaked key. Don’t just create a new one. The old one keeps working until you delete it.
- Cap spending. Set a hard monthly limit so a second leak can’t empty your account.
- Check usage and billing. Note the dates, models and amounts that weren’t yours. Take screenshots.
- Find out how it leaked, so you don’t leak the new key the same way (see the next section).
- Ask the provider for a refund with the evidence from step 3.
- Move the key server-side before you put the new one anywhere.
OpenAI
Go to the API keys page in the OpenAI dashboard, delete the exposed key and create a new one. OpenAI’s key safety guide recommends setting monthly spend limits for the organization or each project and turning on hard enforcement. Spend alerts on their own only email you; they don’t stop requests. Even with hard enforcement, spend can go slightly over the limit, because the cut-off isn’t instant. Then review the Usage page and contact OpenAI through help.openai.com.
Anthropic (Claude)
In the Claude Console, open API keys, click the menu next to the key and choose Delete API key. Anthropic’s key guide suggests spend limits on the Billing page (or careful auto-reload limits on standard accounts) as a guard against leaked keys. Anthropic also takes part in GitHub’s secret scanning program: if a Claude key turns up in a public GitHub repository, Anthropic deactivates it automatically and emails you. If you got that email, the key is already dead, but you still need to fix the code that leaked it.
Google Gemini
Generate a new key in Google AI Studio or the Cloud console, update your app, then disable or delete the old one. Google’s API key docs also recommend restricting each key to the Gemini API and to the apps or addresses that should use it, and auditing usage in your billing reports.
Other paid APIs
The same steps apply to Groq, OpenRouter, ElevenLabs, Replicate, Resend, Twilio or anything else that bills per request. Revoke, replace, check usage. A leaked Stripe secret key (sk_live_...) or Supabase secret key (service_role or sb_secret_...) is worse than an AI key, because it opens your payments or your whole database. Treat those as an emergency.
How to check if your API key is exposed
In a web app (Lovable, Bolt.new, v0, Replit)
- Open your live site in a private window.
- Open developer tools (F12 or Cmd+Option+I) and go to Sources (Chrome) or Debugger (Firefox).
- Search across all files (Cmd+Option+F or Ctrl+Shift+F) for each of these prefixes:
| Search for | What it usually is |
|---|---|
sk-proj-, sk- |
OpenAI |
sk-ant- |
Anthropic (Claude) |
AIza |
Google, including Gemini |
gsk_ |
Groq |
sk-or- |
OpenRouter |
sk_live_, rk_live_ |
Stripe secret or restricted key |
service_role, sb_secret_ |
Supabase secret key |
- Open the Network tab, use the AI feature, and look at where requests go. If your browser calls
api.openai.com,api.anthropic.comorgenerativelanguage.googleapis.comdirectly, the key is in the browser, even if your search missed it. - Check whether your site serves source maps (files ending in
.map). They hand out your original source code, comments and all.
Some keys are meant to be public: the Supabase anon or publishable key (sb_publishable_...), Stripe’s publishable key (pk_live_...), Firebase web config and analytics keys. Finding those is fine. Finding anything from the table above is not.
In a mobile app (Expo, Rork, FlutterFlow)
A store app is no safer than a website. Expo’s environment variable docs say it plainly: anything in an EXPO_PUBLIC_ variable is visible in plain text in the compiled app. The same goes for keys hard-coded in Dart, Swift or Kotlin, or passed in at build time. Anyone can download your app, unzip it and search the bundle.
To check, search your project for the prefixes above and for EXPO_PUBLIC_. If an AI provider’s key is in any EXPO_PUBLIC_ variable, or anywhere in the app code, assume it’s public.
In your code history and tools
Search your GitHub repository, including old commits, for the same prefixes. Deleting a key in a later commit doesn’t remove it from history, so a key that was ever committed to a public repo has to be revoked. GitHub’s push protection is on by default for users and blocks many known key formats from being pushed to public repositories, but it doesn’t catch everything and doesn’t help with private repos unless it’s turned on.
Also think about where else you pasted the key: AI chat windows, Discord or Slack messages, screenshots, Loom videos, a .env file sent to a freelancer. If it went somewhere you don’t control, rotate it.
Why AI builders put API keys in the frontend
Because it’s the shortest path to “it works”. Calling the model from the page needs no server, no deploy step and no secrets setup, so a tool optimising for a working demo picks it.
The frameworks warn against it. Vite’s env docs say VITE_ variables should not contain API keys because they’re bundled into your code at build time. Next.js inlines every NEXT_PUBLIC_ variable into the JavaScript sent to the browser. OpenAI and Google both say never to put keys in browser or mobile code. Lovable’s own Secrets docs say keys like OPENAI_API_KEY belong in Secrets, which only reach Edge Functions, while VITE_ values end up in the browser.
So the fix isn’t a setting. The call to the AI provider has to move to a server.
How to hide an API key in a Lovable, Bolt or Expo app
The pattern is the same for every stack: your app calls your server, and only your server calls the AI provider. The server holds the key, checks who’s asking and limits how much each user can spend.
If your app already uses Supabase (most Lovable, Bolt and Rork apps do), an Edge Function is the easiest server. On Lovable Cloud, add the key under More → Settings → Secrets and ask Lovable to move the AI call into an Edge Function. With your own Supabase project, set the secret from the CLI:
supabase secrets set OPENAI_API_KEY=sk-proj-your-new-key
Step 1: The Edge Function
This function only answers signed-in users, allows each of them 50 AI requests a day, and keeps the key on the server. It assumes a small ai_usage table (step 2).
// supabase/functions/ai-chat/index.ts
import { createClient } from "npm:@supabase/supabase-js@2";
const DAILY_LIMIT = 50;
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
Deno.serve(async (req) => {
if (req.method === "OPTIONS") return new Response("ok", { headers: corsHeaders });
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { ...corsHeaders, "Content-Type": "application/json" },
});
// 1. Who is asking? Reject anyone who isn't signed in.
const token = (req.headers.get("Authorization") ?? "").replace("Bearer ", "");
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!, // server only, never in the app
);
const { data: { user } } = await supabase.auth.getUser(token);
if (!user) return json({ error: "Not signed in" }, 401);
// 2. Rate limit: count this user's requests in the last 24 hours.
const since = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const { count } = await supabase
.from("ai_usage")
.select("id", { count: "exact", head: true })
.eq("user_id", user.id)
.gte("created_at", since);
if ((count ?? 0) >= DAILY_LIMIT) return json({ error: "Daily limit reached" }, 429);
// 3. Validate input so nobody can send a novel per request.
const { prompt } = await req.json();
if (typeof prompt !== "string" || prompt.length === 0 || prompt.length > 4000) {
return json({ error: "Invalid prompt" }, 400);
}
await supabase.from("ai_usage").insert({ user_id: user.id });
// 4. Only the server talks to OpenAI. The key never leaves Supabase.
const ai = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: Deno.env.get("OPENAI_MODEL")!, // e.g. set with `supabase secrets set`
input: prompt,
max_output_tokens: 800,
}),
});
if (!ai.ok) return json({ error: "AI request failed" }, 502);
const data = await ai.json();
// The raw Responses API returns an `output` array; collect its text parts.
const text = (data.output ?? [])
.flatMap((item: any) => item.content ?? [])
.filter((part: any) => part.type === "output_text")
.map((part: any) => part.text)
.join("");
return json({ text });
});
A few choices here matter more than the code style:
- The model and output size are set on the server. If the browser could choose them, an attacker would pick the most expensive model and the longest answer.
- The limit is per user, not global. One abusive account can’t use up everyone’s budget.
- Prompt length is capped. Long inputs cost money too.
Set OPENAI_MODEL as a secret too, to whichever model your app already uses, so you can change it without touching the code.
Step 2: The usage table
create table public.ai_usage (
id bigint generated always as identity primary key,
user_id uuid not null references auth.users (id) on delete cascade,
created_at timestamptz not null default now()
);
create index ai_usage_user_time on public.ai_usage (user_id, created_at);
-- Only the Edge Function (service role) writes here. No policies = no access for app users.
alter table public.ai_usage enable row level security;
If you get “permission denied for table” on a new table like this one, that’s the Supabase change from 30 October. The 42501 guide explains the safe grant.
Step 3: Call it from the app
In a web app or an Expo app, supabase-js sends the signed-in user’s token for you:
const { data, error } = await supabase.functions.invoke("ai-chat", {
body: { prompt },
});
if (error) {
// 401: ask the user to sign in. 429: show "you've hit today's limit".
}
Then delete every trace of the AI key from the frontend: .env entries with VITE_, NEXT_PUBLIC_ or EXPO_PUBLIC_ prefixes, hard-coded strings, and the old direct fetch to the provider. Deploy, then run the checks above again on the live site or a fresh build. In a mobile app, the old key is still inside every copy already installed, so it has to stay revoked, and the old app version will lose its AI features until people update. That’s the price of the fix, and it’s why it’s worth doing before launch, not after.
If your app doesn’t use Supabase, the same function works as a Next.js route handler, a Cloudflare Worker, a Firebase Cloud Function or a small server on your host. The rules don’t change: auth check, per-user limit, server-chosen model, key in a server-only secret.
How to get a refund for charges on a stolen API key
There’s no guarantee, and policies differ. In the Railway case, Railway reported that AWS Bedrock and Google Gemini refunded affected customers under their existing fraud policies, OpenAI reviewed claims case by case, and OpenRouter enforced its no-refund terms. That’s a useful picture of how each provider treats fraud, even when you weren’t part of a platform breach.
Your best chance comes from moving fast and being specific:
- Revoke the key before you ask. Providers are less sympathetic about usage that continued after you knew.
- Give the exact time window, the key’s name or last characters, the models used and the amount.
- Explain how it leaked and what you’ve changed. “Key was in our frontend bundle; we’ve moved AI calls to a server function and revoked the key” reads very differently from “we got hacked”.
- If a platform you use was breached (like Railway), follow its claim process too.
If the provider refuses and the charge went through on a card, you can raise it with your card issuer, but give the provider a chance to answer first.
Leaked API key checklist
- Old key revoked, new key created
- Hard spend limit set with each AI provider
- Usage and billing reviewed and screenshotted
- Refund request sent with dates, amounts and the fix
- No AI provider key in any
VITE_,NEXT_PUBLIC_orEXPO_PUBLIC_variable - Prefix search of the live site, app bundle and GitHub history comes back clean
- Browser and app never call the AI provider directly
- Server function checks the user, limits requests per user and sets the model
- Source maps not served in production
- Keys stored only in your host’s or Supabase’s secrets, not in chats or shared files
When to bring in a developer
If you caught the leak early, the key is revoked and your app only has one AI feature, you can probably follow this guide yourself in an afternoon. It’s worth getting help when the AI calls are spread across many screens, when it’s a mobile app with users on old versions, when the leaked key was a Stripe or Supabase secret key (which means checking payments and data, not just bills), or when you can’t tell how the key got out.
This is the kind of work I do: moving AI and payment calls out of the frontend, adding per-user limits, and checking the rest of an AI-built app for the next leak before someone else finds it. If your app came from Lovable, start with how I fix Lovable apps; for Bolt.new, see fixing Bolt.new apps; for a Rork or Expo app, see fixing Rork apps. Or tell me what happened and I’ll tell you what I’d check first. If you’re on Supabase, also run the Lovable data leak check: an app that leaked a key often has open tables too.
FAQ
Is it safe to put an OpenAI API key in the frontend?
No. Anything in frontend code, including VITE_, NEXT_PUBLIC_ and EXPO_PUBLIC_ variables, is readable by anyone who loads your site or downloads your app. OpenAI’s own guidance is never to deploy a key in browsers or mobile apps. Call your own server function instead and keep the key there.
How do I know if someone is using my API key?
Check the provider’s usage page for requests at times, volumes or models you don’t recognise. Sudden spikes, usage overnight or calls to models your app never uses are the usual signs. If you’re not sure, rotate the key anyway: it costs a few minutes and removes the doubt.
Will OpenAI refund charges from a stolen API key?
Sometimes, but it’s decided case by case and isn’t guaranteed. Revoke the key first, then contact OpenAI through help.openai.com with the dates, amounts and models involved, and explain how the key leaked and what you’ve fixed. Setting a hard spend limit is the only reliable way to cap your loss next time.
Is the Supabase anon key a secret?
No. The anon or publishable key is meant to be in the frontend, and it’s only safe when row-level security protects every table. The service_role or secret key is different: it bypasses all security rules, must never be in the frontend, and should be rotated if it ever was.
Does deleting the key from GitHub fix a leak?
No. The key stays in your repository’s history, and automated scanners may have copied it within minutes of the push. Revoke it with the provider, create a new one, and keep the new one in your host’s secrets, never in the code.
Further reading
- Best practices for API key safety (OpenAI)
- API key best practices (Anthropic)
- Using Gemini API keys (Google)
- Secrets (Lovable)
- Edge Function environment variables (Supabase)
- Environment variables in Expo (Expo)
- Incident report: October security incident (Railway)