Stop strangers running up your OpenAI bill
Your AI app's chat or generate button can run up a big OpenAI or Claude bill overnight. Test it in 5 minutes, then add login checks, limits and spend caps.
You added an AI feature to your app. A "Generate" button, a chat box, a "summarise this" tool. You built it with Lovable, Bolt, Cursor, Replit or v0, it works, and it costs you a few cents a day.
Then one morning the email arrives: your OpenAI or Anthropic account hit its limit, or your card was charged far more than usual. Nobody hacked your database. Someone found the address your AI button calls and pointed a script at it, using your app as a free AI service and leaving you the bill.
This is sometimes called "denial of wallet", and AI-built apps are an easy target because the AI feature usually ships the moment it first works. This guide shows how to check your own app in about five minutes, and the five fixes that stop it, from the most urgent to the nice-to-have.
How the bill gets run up
There are three common ways, and they get worse in this order.
1. The AI key is in the browser. The app calls api.openai.com or api.anthropic.com directly from the page, so the key is in your JavaScript. Anyone can copy it and use it for anything, not just your feature. We cover this one in depth in Your API key is probably sitting in your JavaScript. If this is you, stop reading and fix that first: rotate the key, then move the call to the server.
2. The key is on the server, but the endpoint answers anyone. The key is safely in a Supabase Edge Function, a Next.js Route Handler or an Express route. But that function doesn't check who is calling. Your page has a login, the function behind it doesn't. A stranger who opens your browser's network tab can see the address and call it with curl, thousands of times.
3. The endpoint needs a login, but has no limit. Better, but sign-up is free. A script can create an account (or ten) and then call your feature in a loop. Without a per-user limit, one account can spend your whole month's budget in an afternoon.
There is also a quieter variant of all three: the browser sends the model name or the whole prompt to your server, and the server passes it straight on. Then anyone can switch your cheap model for the most expensive one, or ask for 30-page essays instead of the two-line summaries your feature makes.
Check your app in 5 minutes
You don't need to read code for this. Open your live app in Chrome or Firefox.
Step 1: watch the request. Open DevTools (F12 or right-click, Inspect), go to the Network tab, then use your AI feature once. Look at the request that fires.
- If it goes to
api.openai.com,api.anthropic.com,openrouter.aiorgenerativelanguage.googleapis.com, your key is in the browser. That's way 1 above. - If it goes to your own domain (like
/api/generate) or toYOUR-PROJECT.supabase.co/functions/v1/..., the key is probably on the server. Good. Keep going.
Step 2: look at what the browser sends. Click the request and open the Payload (or Request) tab. If you see model, max_tokens, temperature or a system prompt in there, the browser is choosing things only your server should choose.
Step 3: call it signed out. Right-click the request, choose Copy as cURL, and paste it into a terminal. Then delete the Authorization header (the line with Bearer ...) and any Cookie header, and run it again.
curl -i -X POST https://YOUR-APP.com/api/generate \
-H "Content-Type: application/json" \
-d '{"prompt":"Say hello"}'
If you get a 401 or 403, the endpoint wants a login. If you get a 200 with an AI answer, anyone on the internet can use your AI feature on your bill. For Supabase, this usually means the function was deployed with JWT checks switched off; Is your Supabase Edge Function open to anyone? explains how to spot and fix that.
Step 4: check for a limit. Signed in with a test account, use the feature 30 or 40 times in a row (or run the copied cURL command in a short loop). If it never says "limit reached", there is no per-user limit.
Only test your own app. Running these checks against someone else's endpoint costs them money and isn't yours to do.
Fix 1: keep the key and the choices on the server
The browser should send only the user's input. The server decides everything else: which model, how long the answer can be, and the instructions around the user's text.
Bad (the browser picks the model and the instructions):
// frontend
fetch("/api/generate", {
method: "POST",
body: JSON.stringify({
model: "the-biggest-model",
system: "You are a helpful assistant",
prompt: userText,
}),
});
Better: the frontend sends { "text": userText } and nothing else. The server fills in a fixed model, a fixed system prompt and a maximum answer length. With OpenAI's Responses API that's max_output_tokens; with Anthropic's Messages API it's the required max_tokens. Pick the smallest number that still works for your feature.
Fix 2: require a login on the server
Hiding the button for signed-out visitors doesn't count. The function itself must check the session and refuse with 401 when there isn't one. Here is the core of a Supabase Edge Function that does that:
import { createClient } from "npm:@supabase/supabase-js@2";
Deno.serve(async (req) => {
const token = (req.headers.get("Authorization") ?? "").replace("Bearer ", "");
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: `Bearer ${token}` } } },
);
const { data: { user } } = await supabase.auth.getUser(token);
if (!user) return new Response("Please sign in", { status: 401 });
// ...limit check and the AI call go here
});
In a Next.js Route Handler the idea is the same: read the session on the server first, return 401 if there's no user, and only then call the AI provider. CORS settings don't protect you here. CORS only limits what other websites can do inside a visitor's browser; curl and scripts ignore it.
Fix 3: give every user a daily limit
A login stops anonymous strangers. A limit stops a free account from spending your month in an hour. You don't need a new service for a simple version; a small table and one function in Supabase will do.
create table public.ai_usage (
user_id uuid not null references auth.users (id) on delete cascade,
day date not null default current_date,
calls int not null default 0,
primary key (user_id, day)
);
-- RLS on and no policies: the browser can't read or change the counter
alter table public.ai_usage enable row level security;
create or replace function public.use_ai_credit(p_limit int)
returns boolean
language plpgsql
security definer
set search_path = ''
as $$
declare
used int;
begin
if auth.uid() is null then
return false;
end if;
insert into public.ai_usage (user_id, day, calls)
values (auth.uid(), current_date, 1)
on conflict (user_id, day)
do update set calls = public.ai_usage.calls + 1
returning calls into used;
return used <= p_limit;
end;
$$;
revoke execute on function public.use_ai_credit(int) from public, anon;
grant execute on function public.use_ai_credit(int) to authenticated;
The function counts calls for the signed-in user only (it uses auth.uid(), never a user ID from the request), so the worst a user can do by calling it directly is use up their own allowance. In the Edge Function above, add this before the AI call:
const { data: allowed, error } = await supabase.rpc("use_ai_credit", { p_limit: 20 });
if (error || !allowed) {
return new Response("Daily limit reached, try again tomorrow", { status: 429 });
}
Set p_limit from your plan: low for free users, higher for paying ones. If your plan or credits live in a table, make sure users can't edit that column themselves; Supabase roles: stop users making themselves admin shows how that goes wrong. Also cap the input size on the server, for example reject any text over 2,000 characters, so one call can't carry a novel.
Fix 4: make sign-up a little harder to automate
If free accounts get AI calls, a script will make free accounts. Turn on email confirmation, and add a CAPTCHA such as Cloudflare Turnstile or hCaptcha to sign-up. Supabase supports both in its auth settings. Our Supabase login settings to check before you launch walks through those switches. If anonymous sign-ins are on, remember that an anonymous user is still a signed-in user to your function; give them a very low limit or none.
Fix 5: set a hard spend cap at the provider
This is your safety net for the day everything else fails. Every major provider now lets you cap spend. Set it today, even if you do nothing else.
- OpenAI: in your organization settings, open the project, go to Limits, and under Spend set a monthly spend limit. Turn on Enforce a hard limit, otherwise it only sends an email and keeps serving requests. OpenAI notes that enforcement isn't instant, so spend can go slightly over.
- Anthropic (Claude): in the Claude Console under Spend limits, set a monthly limit for your organization, or put your app in its own workspace and give that workspace a lower limit. The docs say spend can take a while to show up, so usage can pass the limit before requests stop.
- OpenRouter: give each key its own credit limit with a daily, weekly or monthly reset. OpenRouter itself recommends a limit on every key.
Use a separate project, workspace or key just for your live app, so a runaway feature can't eat the budget you use for development. When the cap is hit, your AI feature will stop working until the next month or until you raise it. That's the point: a broken button is much cheaper than a surprise bill. Make your app show a friendly "AI is busy, try later" message on a 429, instead of a blank error.
A prompt for your AI tool
Paste this into Lovable, Bolt, Cursor, Replit or v0:
Review every AI feature in this app. For each one: 1) confirm the AI provider key is only used on the server, never in frontend code or a NEXT_PUBLIC_ / VITE_ variable; 2) make the server endpoint return 401 when there is no valid session; 3) set the model, system prompt and maximum output tokens on the server and ignore any model or token settings sent by the browser; 4) reject input longer than 2,000 characters; 5) add a per-user daily limit stored in a table users can't edit, returning 429 when it's reached. List each endpoint and what you changed. Don't print any key values.
Then set the provider spend cap yourself. That part lives in your provider dashboard, not in your code.
The short checklist
- The AI key never reaches the browser.
- The AI endpoint returns
401when called signed out. - The server picks the model, the instructions and the answer length.
- Each user has a daily limit, stored where they can't change it.
- Input length is capped on the server.
- Sign-up has email confirmation and a CAPTCHA.
- A hard spend cap is on at OpenAI, Anthropic or OpenRouter, on a key or project used only by your live app.
Check your app
Start with the outside view. Run the free Greenlight Scan on your live URL: in about two minutes you get a security score and your worst problem by name, such as an OpenAI or Anthropic key sitting in your JavaScript. The $19 Full Scan, a one-time payment, verifies you own the site and adds the deeper checks, including API routes that return data without a login, with a fix prompt for your AI tool for every finding.
Per-user limits, a model name the browser can change, or a plan column that unlocks more AI calls live in your code, where an outside scan can't see them. If your app takes payments or stores personal data, the $79 Launch Audit also reads your GitHub code: a deep AI review that includes your AI features and abuse and business logic, with every finding double-checked by a second AI and a one-page launch verdict. It's automated, not a pentest, but it's built for exactly these mistakes. And because AI tools change code fast, Greenlight Watch ($9 a month) re-checks your live app every week and emails you when something new turns up, like a key that slipped back into the frontend.
The Friday leak report
One short email a week: the newest ways AI-built apps leak data, and the one-line fix for each. No spam, unsubscribe any time.