Why is my endpoint open if the key is on the server?
Because the endpoint does whatever the request asks. Moving the key to the server stops people from copying it. It does nothing to stop them from using your server as a free relay to the same model, on your bill. OWASP lists this as LLM10:2025 Unbounded Consumption and names one form of it "Denial of Wallet": high volumes of requests that run up cost-per-use charges.
Five gaps show up again and again in AI features built quickly:
- No sign-in check, or one the public key passes. On Supabase, Edge Functions check the
Authorizationheader by default, but Supabase's own docs say publishable and secret keys "are not JWTs, but the check still accepts them", and that "the check alone doesn't authenticate a caller that sends only an API key" (Supabase: Authorization headers). Your publishable key is in every visitor's browser. - No per-user limit. One account can send ten thousand requests as easily as ten.
- The browser chooses the model, the maximum output and the whole prompt, including the system message.
- CORS is treated as protection. CORS is a rule that browsers apply to scripts running on web pages (MDN: CORS). A script run from a terminal never asks for permission. Our CORS guide covers what it is actually for.
- A free tier anyone can join again and again, with a throwaway email each time.
What does the broken version look like?
This is the shape of many generated chat functions. It works, and the key stays secret:
// supabase/functions/chat/index.ts (the version to replace)
Deno.serve(async (req) => {
const { messages, model, max_tokens } = await req.json()
const r = 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, max_tokens, messages }),
})
return new Response(await r.text(), {
headers: { "Access-Control-Allow-Origin": "*" },
})
})
Nothing asks who is calling. model, max_tokens and messages come straight from the request, so a caller can pick your most expensive model, ask for the longest possible answer and replace your system message with their own work. The CORS header is irrelevant outside a browser.
How do I fix it on the server?
The browser should send one thing: the user's message.
1. Count usage in a table the browser cannot touch
create table public.ai_usage (
user_id uuid not null references auth.users on delete cascade,
day date not null default current_date,
requests int not null default 0,
primary key (user_id, day)
);
alter table public.ai_usage enable row level security;
-- no policies: the browser can neither read nor write this table
create or replace function public.take_ai_credit()
returns boolean
language sql
security definer
set search_path = ''
as $$
insert into public.ai_usage (user_id, day, requests)
values (auth.uid(), current_date, 1)
on conflict (user_id, day)
do update set requests = public.ai_usage.requests + 1
where public.ai_usage.requests < 50 -- the daily limit
returning true;
$$;
The function adds one to today's count for the signed-in user and returns nothing once they reach 50. The limit lives in the database, so no request can change it.
2. Check the user, cap the input, then count
// supabase/functions/chat/index.ts (the fixed version)
import { createClient } from "npm:@supabase/supabase-js@2"
import OpenAI from "npm:openai"
const INSTRUCTIONS = "You answer questions about recipes saved in this app. Keep answers short."
const MODEL = Deno.env.get("OPENAI_MODEL")! // set by you, never by the request
const MAX_OUTPUT_TOKENS = 600
const MAX_INPUT_CHARS = 4000
const openai = new OpenAI({ apiKey: Deno.env.get("OPENAI_API_KEY") })
Deno.serve(async (req) => {
const auth = req.headers.get("Authorization") ?? ""
const supabase = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!, // or your publishable key
{ global: { headers: { Authorization: auth } } },
)
// A real signed-in user, not the public key
const { data, error } = await supabase.auth.getClaims(auth.replace("Bearer ", ""))
const claims = data?.claims
if (error || !claims?.sub || claims.role !== "authenticated" || claims.is_anonymous) {
return new Response("Sign in first", { status: 401 })
}
const { message } = await req.json()
if (typeof message !== "string" || !message || message.length > MAX_INPUT_CHARS) {
return new Response("Message missing or too long", { status: 413 })
}
const { data: allowed } = await supabase.rpc("take_ai_credit")
if (allowed !== true) return new Response("Daily limit reached", { status: 429 })
const r = await openai.responses.create({
model: MODEL,
instructions: INSTRUCTIONS,
input: message,
max_output_tokens: MAX_OUTPUT_TOKENS,
})
return Response.json({ reply: r.output_text })
})
3. Know why each line is there
getClaimsverifies the token's signature (Supabase: getClaims). A signed-in user's token hasroleset toauthenticatedand their user id insub; a token made from the anon key hasroleset toanonand nosub(Supabase: JWT fields). Theis_anonymouscheck matters if you turned on anonymous sign-ins.instructionsis OpenAI's field for a system message, andmax_output_tokensis an upper bound on generated tokens, reasoning tokens included (OpenAI API reference: create a response). Both now live in code the browser never sees.- The count happens before any money is spent.
Using Next.js instead? The same three checks go at the top of the route handler or server action, before the call to the provider. Our fix prompt for routes that require sign-in by default gives your AI coding tool the instruction in one paste.
What limits can I set with OpenAI and Anthropic?
Set these today. They do not replace the checks above: they cap the damage if something slips past them.
OpenAI. Organizations and projects can have a monthly spend limit. With Enforce a hard limit turned on, requests fail with a 429 and the code project_spend_limit_exceeded once tracked spend reaches it. Without it, the limit only notifies you. OpenAI also says enforcement is not instantaneous, so spend can slightly exceed the amount (OpenAI: Spend limits). Its key safety page puts it plainly: "Spend alerts alone don't stop API traffic" (OpenAI Help Center). Each project can also restrict which models it may use and set a rate limit per model, and a key created in a project is scoped to that project (OpenAI Help Center: projects).
Anthropic. You can set an organization spend limit below your usage tier's monthly cap. When usage reaches it, requests return HTTP 400 with invalid_request_error until the limit resets or you raise it. Workspaces can have their own lower spend and rate limits, though Anthropic notes that a spend limit on the default workspace might not count some usage, such as the Console playground (Claude docs: Rate limits).
Our rule of thumb: one project or workspace per app and per environment, each with its own key and its own hard limit. A staging bug or a key on a laptop then cannot spend production's budget. After you set a limit, check on a throwaway project that hitting it really returns the error you expect.
How do I stop endless free sign-ups?
A per-user quota only works if a user is hard to mint. Supabase Auth supports hCaptcha and Cloudflare Turnstile on sign-up, sign-in and password reset forms, under Bot and Abuse Protection in the dashboard (Supabase: CAPTCHA). Turn on Confirm email so users confirm their address before they can sign in (Supabase: General configuration).
Then size the free quota so that a hundred fake accounts cost you an amount you can shrug at. Work it out from your own numbers: daily limit, times the maximum output you allow, times your model's price. Limits on sign-up and password reset requests per IP address help too; the login rate limiting guide shows how to test them.
How will I notice before the invoice does?
Your ai_usage table is already a log. Once a day, look at the heaviest users:
select user_id, requests
from public.ai_usage
where day = current_date
order by requests desc
limit 10;
A user at the limit every day is either your best customer or a script. Compare the total with the provider's Usage page. If the provider shows far more requests than your table, something calls the provider without going through your counter, and that something is the next thing to find.
What we would skip: hiding the endpoint's address, renaming the function, or locking CORS down and calling it done. None of those changes what a request from a terminal can do.
Try it on your own app
Call your own AI endpoint from a terminal, signed out:
curl -i -X POST https://YOUR-PROJECT.supabase.co/functions/v1/chat \
-H "Content-Type: application/json" \
-d '{"message":"hello"}'
curl -i -X POST https://YOUR-PROJECT.supabase.co/functions/v1/chat \
-H "Authorization: Bearer YOUR_PUBLISHABLE_KEY" \
-H "Content-Type: application/json" \
-d '{"message":"hello"}'
Both should answer 401. If either one returns a reply from the model, the endpoint is open. Then, signed in as a test user, add "model" and "max_tokens" fields to the body and confirm nothing changes, and send requests until you see the 429. Run that last part on a staging copy if you can, since each request costs a little.