12 min read · Updated 2026-11-29
Rate limit AI calls per user in a Supabase Edge Function
Require a signed-in user and reserve each AI call in Postgres so a public edge function cannot be looped into a surprise bill.
Putting the OpenAI key in a Supabase secret is the right first move. It is not the whole fix. The function URL is still on the internet. If it answers anyone, a bot can call it all night. The key stays hidden, and the bill still arrives.
A variable in the function's memory is also not a cap. Each request can run in a fresh isolate, and two requests at the same time will not see each other's count. Store the count in Postgres, and increment it in one statement so two parallel calls cannot both sneak through.
The table and the one statement that matters
Run this in the Supabase SQL editor. The function inserts the first call of the day, or adds one, and refuses once the row is already at the cap. No policies for the browser role: only the edge function, using the service role, should touch this table.
create table if not exists ai_quota (
user_id uuid not null,
day date not null,
used int not null default 0,
primary key (user_id, day)
);
alter table ai_quota enable row level security;
create or replace function reserve_ai_call(uid uuid, cap int)
returns boolean
language plpgsql
security definer
set search_path = public
as $$
declare
new_used int;
begin
insert into ai_quota (user_id, day, used)
values (uid, current_date, 1)
on conflict (user_id, day)
do update set used = ai_quota.used + 1
where ai_quota.used < cap
returning used into new_used;
return new_used is not null;
end;
$$;
revoke all on function reserve_ai_call(uuid, int) from public, anon, authenticated;
grant execute on function reserve_ai_call(uuid, int) to service_role;The edge function
The function checks the user's session with the anon key and their JWT, then spends one unit of quota with the service role, then calls the model. The service role key never goes to the browser. OPENAI_API_KEY is a function secret, not a column.
import { createClient } from "https://esm.sh/@supabase/supabase-js@2";
const DAILY_CAP = 20;
Deno.serve(async (req) => {
if (req.method !== "POST") {
return new Response("Method not allowed", { status: 405 });
}
const authHeader = req.headers.get("Authorization") ?? "";
const userClient = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_ANON_KEY")!,
{ global: { headers: { Authorization: authHeader } } },
);
const { data: userData, error: userError } = await userClient.auth.getUser();
if (userError || !userData.user) {
return Response.json({ error: "Sign in first." }, { status: 401 });
}
const admin = createClient(
Deno.env.get("SUPABASE_URL")!,
Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!,
);
const { data: allowed, error: quotaError } = await admin.rpc("reserve_ai_call", {
uid: userData.user.id,
cap: DAILY_CAP,
});
if (quotaError) {
return Response.json({ error: "Could not check today's limit." }, { status: 500 });
}
if (!allowed) {
return Response.json({ error: "Daily AI limit reached." }, { status: 429 });
}
const openaiKey = Deno.env.get("OPENAI_API_KEY");
if (!openaiKey) {
return Response.json({ error: "Server is missing the AI secret." }, { status: 500 });
}
const body = await req.json().catch(() => ({}));
const message = String(body.message ?? "").slice(0, 4000);
const ai = await fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
Authorization: `Bearer ${openaiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gpt-4o-mini",
messages: [{ role: "user", content: message }],
}),
});
if (!ai.ok) {
return Response.json({ error: "The model request failed." }, { status: 502 });
}
const payload = await ai.json();
const text = payload?.choices?.[0]?.message?.content ?? "";
return Response.json({ text });
});Prompt you can paste into Cursor
Paste this into Lovable, Bolt, or Cursor
Add a daily cap to my Supabase Edge Function that calls OpenAI. Use a Postgres function reserve_ai_call(uid, cap) that inserts or increments ai_quota for the current date in one statement, and returns false when the row is already at the cap. Call it with the service role only after supabase.auth.getUser() succeeds. Revoke execute on that function from anon and authenticated. Keep OPENAI_API_KEY in function secrets. Do not create a NEXT_PUBLIC variable. Return 401 when signed out and 429 when the cap is hit. Do not send a test prompt to OpenAI.