Guide
How to stop someone running up your OpenAI bill through a Supabase Edge Function
MondayMedic checks for common public mistakes. It is not a full security audit, and a good score does not mean your app is safe.
Paste code into our free API key leak checker.
Check your live app first. Paste your app's public link into the free MondayMedic check. It reads only public pages and scripts, takes about a minute and needs no account. It flags secret keys in the browser (including AI keys) and Supabase tables the public key can read. It does not call your Edge Functions or change data, and it is not a full security audit.
The short answer
Moving your OpenAI key into a Supabase Edge Function keeps the key secret, but it doesn't stop the spending. The function is now the public door: anyone who can call it can make OpenAI calls on your account. To close it:
- Check who is calling inside the function and reject anyone who isn't a signed-in user.
- Limit calls per user, per minute and per day, before you call OpenAI.
- Cap every call: fix the model on the server, limit input length and set a maximum output length.
- Set a spend limit on the OpenAI project the key belongs to, so a bug can't cost more than you planned.
Why is this so easy to miss?
Apps built with Lovable or Bolt usually do the right first step: the AI key goes into an Edge Function secret, not the browser. The function then gets called from the browser with supabase.functions.invoke. That works, so nobody looks again.
But Supabase's docs note that the default verify_jwt check also accepts the project's public publishable key, so on its own it doesn't prove a real user is calling. And even with a proper user check, anyone can sign up for a free account and get a valid token. Without a per-user limit, one script can call your function thousands of times. In October 2026, builders on X shared exactly this gap: an AI route in a Next.js and Supabase app that lacked the per-user rate limit the app's other AI routes had.
How do I check whether my Edge Function is open?
- Find the functions that cost money. In the Supabase dashboard, open Edge Functions and note every function that calls OpenAI, Anthropic, an image model or any other paid API.
- Check
verify_jwt. Insupabase/config.toml, look forverify_jwt = falseon those functions. False means the platform lets any request through to your code. - Call it logged out. Open your live app in a private window and run this in the browser console, using your own project URL, function name and public key:
A// In your browser console, logged out, on your live app: const r = await fetch("https://YOUR-PROJECT.supabase.co/functions/v1/YOUR-FUNCTION", { method: "POST", headers: { "Content-Type": "application/json", "apikey": "YOUR-PUBLISHABLE-OR-ANON-KEY" }, body: JSON.stringify({ message: "hi" }) }); console.log(r.status, await r.text());401is what you want. A200with an AI reply means anyone on the internet can spend your money. - Call it fast as a real user. Signed in, send 20 or 30 requests in a row. If every one succeeds, there's no per-user limit.
- Look at the bill shape. In your OpenAI usage page, a sudden spike with no matching growth in users is the usual sign.
How do I add a rate limit to a Supabase Edge Function?
Supabase's own rate limiting example uses Upstash Redis, which works well in Edge Functions because it talks over HTTP. Store UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN and OPENAI_API_KEY as function secrets, then check the user and the limits before calling OpenAI:
// supabase/functions/chat/index.ts
import { createClient } from "npm:@supabase/supabase-js@2";
import { Ratelimit } from "npm:@upstash/ratelimit";
import { Redis } from "npm:@upstash/redis";
const redis = new Redis({
url: Deno.env.get("UPSTASH_REDIS_REST_URL")!,
token: Deno.env.get("UPSTASH_REDIS_REST_TOKEN")!,
});
const perMinute = new Ratelimit({ redis, prefix: "chat:min", limiter: Ratelimit.slidingWindow(10, "1 m") });
const perDay = new Ratelimit({ redis, prefix: "chat:day", limiter: Ratelimit.fixedWindow(100, "1 d") });
Deno.serve(async (req) => {
// 1. Who is calling? Reject anyone who isn't a signed-in user.
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: req.headers.get("Authorization") ?? "" } } },
);
const { data: { user } } = await supabase.auth.getUser();
if (!user) return new Response("Unauthorized", { status: 401 });
// 2. Per-user limits, checked before any money is spent.
if (!(await perMinute.limit(user.id)).success || !(await perDay.limit(user.id)).success) {
return new Response("Too many requests", { status: 429 });
}
// 3. Cap the input and the output.
const body = await req.json().catch(() => null);
const message = body?.message;
if (typeof message !== "string" || message.length === 0 || message.length > 4000) {
return new Response("Bad request", { status: 400 });
}
const res = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: { "Authorization": `Bearer ${Deno.env.get("OPENAI_API_KEY")}`, "Content-Type": "application/json" },
body: JSON.stringify({
model: "gpt-4o-mini", // fix the model on the server, never take it from the browser
max_completion_tokens: 500, // hard cap on output per call
messages: [{ role: "user", content: message }],
}),
});
return new Response(await res.text(), { status: res.status, headers: { "Content-Type": "application/json" } });
});
Pick numbers that fit your app; the 10 per minute and 100 per day above are a starting point, not a rule. If you use Lovable or Bolt, you can paste this guide's steps into the chat and ask it to add the user check, both limits and the output cap to each function that calls a paid API, then run the checks above again.
What else limits the damage?
- OpenAI spend limits. OpenAI's docs describe spend limits you can set for an organization or a project, separate from its rate limits. Set one on the project your app uses.
- One project and key per app. Then a leak in one app can't drain the budget of another, and you can rotate one key without touching the rest.
- Never take the model from the browser. If the request body chooses the model, someone can switch your cheap model for the most expensive one.
- Watch for abuse at sign-up. If sign-ups are open and free, consider email confirmation or a captcha so one person can't create hundreds of accounts to get around per-user limits.
- Keep the secret key out of the browser. Never call the function from the browser with the
service_roleor secret key. It bypasses RLS and makes every caller look the same. See anon key vs service_role key.
Related guides
- How to check and fix open Supabase RLS in a Lovable app
- Is the Supabase anon key safe to expose?
- Does a Supabase view bypass RLS?
Want a weekly look from the outside? Run the free check on your live app.
FAQ
Can someone run up my OpenAI bill through my Lovable app?
Yes, if the Edge Function that calls OpenAI accepts calls from anyone, or from any signed-up account with no per-user limit. Your OpenAI key stays secret on the server, but the function itself is a public door that spends money on every call.
Does verify_jwt stop abuse of my Edge Function?
Not on its own. verify_jwt is on by default and rejects requests without a valid token, but Supabase's docs note it also accepts the public publishable key, and anyone can sign up for a free account to get a valid user token. Check the user in your code and limit calls per user.
How do I rate limit a Supabase Edge Function?
Supabase's own example uses Upstash Redis: look up the signed-in user, then allow a fixed number of calls per user per minute and return a 429 when they go over. Add a daily cap per user and a maximum output length on every OpenAI call.
Should I set a spend limit in OpenAI too?
Yes. OpenAI lets you set spend limits for an organization or a project, separate from its rate limits. Use a separate project and key for each app so one leaky app can't use up the budget of another.
Will MondayMedic catch this?
The free check reads your live app from the outside and flags secret keys in the browser and Supabase tables the public key can read. It does not call your Edge Functions or test their limits, so use the steps in this guide for that.