Call OpenAI from a Supabase Edge Function, not the browser
Move an OpenAI call out of your React app into a Supabase Edge Function that checks the user, fixes the model and limits requests, then test it with curl.
· 8 min read
Your app has an AI feature, and right now the browser talks to OpenAI directly. Maybe the key sits in a VITE_OPENAI_API_KEY variable, maybe the SDK runs with dangerouslyAllowBrowser: true. It works, but every visitor downloads the key along with your JavaScript. If your app already runs on Supabase, as most Lovable and Bolt apps do, the clean fix is to move that one call into an Edge Function.
If the key is already public, revoke it first. The order of operations for that, and how to check usage, is in OpenAI API key exposed in your frontend. This guide is the rebuild: a function you can copy, the client change, and four tests that prove a stranger can't use it.
Why "just move it to the server" often goes wrong
An Edge Function runs on Supabase's servers, so a key read inside it never reaches the browser. That part is easy. The trouble is what an AI assistant tends to write when you ask it to "move the OpenAI call to an Edge Function": a function that takes model, messages and max_tokens from the request body and forwards them. The key is hidden, but now your endpoint is the leak. Anyone who finds the URL in your bundle can send any prompt to any model, and you pay.
A few things make this easy to miss on Supabase:
- The platform check is not a login check. By default the gateway inspects the
Authorizationheader before your function runs (verify_jwt). Supabase's Securing Edge Functions page notes that this check also accepts the publishable and secret API keys, so a caller holding only your public key can get through it. Who the user is, and whether they may call the function, is something your code has to decide. - The function URL is public. It sits in your JavaScript next to the project URL and the anon key, and both of those are meant to be public.
- CORS makes people turn things off. The first browser call usually fails on the preflight request. Disabling auth to "fix" it is a common wrong turn: the real fix is to answer
OPTIONSwith the right headers, as the CORS guide shows.
So the function needs four properties: the key lives only on the server, only signed-in users get through, the server decides the model, prompt and token limit, and each user has a daily cap.
The function
Create it with the CLI (supabase functions new ask-ai) or ask your builder to create supabase/functions/ask-ai/index.ts. Put the key in the project's secrets, never in a file that gets committed:
supabase secrets set OPENAI_API_KEY=sk-proj-...
Custom secret names can't start with SUPABASE_, which is reserved for the variables Supabase injects. The environment variables docs list those defaults; Supabase is moving from the legacy anon key variable to SUPABASE_PUBLISHABLE_KEYS, so the code below reads the new one and falls back to the old.
The rate limit uses a small table. Run this in the SQL Editor:
create table public.ai_requests (
id bigint generated always as identity primary key,
user_id uuid not null default auth.uid() references auth.users(id),
created_at timestamptz not null default now()
);
alter table public.ai_requests enable row level security;
create policy "insert own" on public.ai_requests
for insert to authenticated with check (user_id = auth.uid());
create policy "read own" on public.ai_requests
for select to authenticated using (user_id = auth.uid());
There is deliberately no delete policy: a user can add rows to their own count but can't clear it. The function itself:
import { createClient } from "npm:@supabase/supabase-js@2";
const cors = {
"Access-Control-Allow-Origin": "https://your-app.example",
"Access-Control-Allow-Headers": "authorization, x-client-info, apikey, content-type",
};
const DAILY_LIMIT = 20;
const MAX_INPUT = 2000;
function reply(status: number, body: unknown) {
return new Response(JSON.stringify(body), {
status,
headers: { ...cors, "Content-Type": "application/json" },
});
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") return new Response("ok", { headers: cors });
if (req.method !== "POST") return reply(405, { error: "POST only" });
const auth = req.headers.get("Authorization") ?? "";
const publishable =
JSON.parse(Deno.env.get("SUPABASE_PUBLISHABLE_KEYS") ?? "{}").default ??
Deno.env.get("SUPABASE_ANON_KEY");
const supabase = createClient(Deno.env.get("SUPABASE_URL")!, publishable, {
global: { headers: { Authorization: auth } },
});
const token = auth.replace(/^Bearer\s+/i, "");
const { data: { user } } = await supabase.auth.getUser(token);
if (!user) return reply(401, { error: "Sign in first" });
const { input } = await req.json().catch(() => ({}));
if (typeof input !== "string" || !input.trim() || input.length > MAX_INPUT) {
return reply(400, { error: `Send 1-${MAX_INPUT} characters` });
}
const since = new Date(Date.now() - 86_400_000).toISOString();
const { count } = await supabase.from("ai_requests")
.select("id", { count: "exact", head: true }).gte("created_at", since);
if ((count ?? 0) >= DAILY_LIMIT) return reply(429, { error: "Daily limit reached" });
await supabase.from("ai_requests").insert({});
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: "gpt-4o-mini",
max_completion_tokens: 500,
messages: [
{ role: "system", content: "You write short product descriptions." },
{ role: "user", content: input },
],
}),
});
if (!r.ok) return reply(502, { error: "AI service error" });
const data = await r.json();
return reply(200, { text: data.choices?.[0]?.message?.content ?? "" });
});
What matters here, line by line:
- The Supabase client inside the function runs as the user: it carries their
Authorizationheader, so the count and insert go through the RLS policies above. No service role or secret key is needed. getUserrejects a missing or fake token, and also a request that carries only the publishable key, because that key is not a user session.- The browser sends only
input. The model, the system prompt and the token limit are constants. Swap in your own model and prompt; just keep them on the server. - OpenAI's error body stays on the server. The client gets a plain 502.
- Set
Access-Control-Allow-Originto your real domain. A browser on another site can't then read your function's responses. CORS doesn't stop curl or a script, which is why the user check matters.
Deploy with supabase functions deploy ask-ai and keep verify_jwt on: it's a cheap first gate, and the code above is the real one.
Change the client
Delete the OpenAI SDK setup, any dangerouslyAllowBrowser option and the VITE_OPENAI_API_KEY variable from the frontend. The call becomes:
const { data, error } = await supabase.functions.invoke("ask-ai", {
body: { input: text },
});
supabase.functions.invoke sends the signed-in user's session for you. If the user isn't signed in, show a sign-in prompt instead of calling the function.
Check it yourself
Run these against the deployed function, not just locally. Replace <project> with your project ref and use your own app's publishable or anon key.
-
Nothing calls OpenAI from the browser. Open the site, DevTools → Network, use the AI feature. The request should go to
<project>.supabase.co/functions/v1/ask-ai. Then search all loaded files (Cmd+Option+ForCtrl+Shift+F) forsk-proj-,api.openai.comanddangerouslyAllowBrowser. All three should find nothing. -
A stranger with only the public key is turned away. This is what anyone can do after reading your bundle:
curl -i -X POST 'https://<project>.supabase.co/functions/v1/ask-ai' \
-H 'apikey: <publishable or anon key>' \
-H 'Content-Type: application/json' \
-d '{"input":"hello"}'
Expect 401. If you get text back, the function is open to anyone.
-
A signed-in user can't change the model. Copy a real request from the Network tab as cURL, add
"model":"gpt-4o"and a hugemax_tokensto the body, and send it. The answer should look the same as before, because the function ignores both. Then send an input longer than your limit: expect400. -
The daily cap works. Lower
DAILY_LIMITto 2, redeploy, call it three times as one user, and expect429on the third. Put the real limit back afterwards.
If any test fails, fix that before you put the new OpenAI key in place.
A prompt for Lovable, Cursor or Claude Code
Move the OpenAI call out of the client into a Supabase Edge Function
named ask-ai.
1. Remove the openai SDK setup, dangerouslyAllowBrowser and any
VITE_/NEXT_PUBLIC_ variable holding the key from client code.
2. In the function, read the key from the secret OPENAI_API_KEY.
Create a Supabase client with the caller's Authorization header and
reject the request with 401 unless auth.getUser() returns a user.
3. Accept only { input: string } of 1-2000 characters. Hard-code the
model, the system prompt and max_completion_tokens in the function.
4. Add a table ai_requests (user_id default auth.uid(), created_at)
with RLS: insert and select own rows only, no delete policy. Allow
20 requests per user per 24 hours, return 429 above that.
5. Answer OPTIONS with CORS headers and allow only my app's origin.
Do not turn off verify_jwt.
6. In the client, call supabase.functions.invoke('ask-ai').
7. Show me the curl command that proves a request with only the
anon key gets 401.
Read the diff before you accept it. The two things assistants most often slip back in are a model field read from the request body and an Access-Control-Allow-Origin of * left in from an example.
Keep it from coming back
The function is safe the day you write it. The risk is the next change: "the AI button doesn't work, fix it" can end with the call back in the browser and a key in a VITE_ variable, and nothing on the page looks different. Rerun the four checks after any change to the AI feature, and if your app also uses Supabase tables directly, read how to check if Row Level Security is on: the same anon key that reaches your function reaches your tables.
ScanYourSite covers the part that tends to regress silently. The free check downloads your page and the scripts it loads and looks for secret keys, including OpenAI and Anthropic keys and the Supabase service_role and sb_secret_ keys, and shows them redacted with the file they're in. The free plan re-checks one site weekly; Pro checks daily and after every deploy, and on Pro, after you verify the domain, it also counts how many rows your tables return to the anon key. It doesn't test your Edge Function's logic: that's what the curl checks above are for.