Call OpenAI from a Supabase Edge Function so your API key never reaches the browser
Last reviewed November 3, 2026 against the providers' current documentation.
The short version
Store the key with supabase secrets set OPENAI_API_KEY=… (or in the dashboard under Edge Function Secrets), write an Edge Function that reads it with Deno.env.get() and calls OpenAI, and have your frontend call that function with supabase.functions.invoke() instead of calling OpenAI. Keep JWT verification on and accept only signed-in users, so the function isn't a free AI proxy for anyone who finds it. Then delete the old key if it was ever in your frontend, and set a hard spend limit on your OpenAI project.
Why it matters
Everything in your frontend, including values from VITE_… variables, is downloaded by every visitor, and OpenAI's API docs say not to expose your key "in any client-side code such as browsers or apps". An Edge Function runs on Supabase's servers: the browser sends the user's question, the function adds the key and calls OpenAI, and only the answer comes back. The key, the model and the system prompt stay on the server. The catch is that the function itself is a public URL. If it accepts anyone, people can use your OpenAI credits through it without ever seeing the key.
Fix it, in this order
If the key was ever in your frontend, replace it
Create a new key on the OpenAI platform's API keys page, ideally in a project used only by this app, and use the new one below. Delete the old key once the function works. Removing it from your code isn't enough, because copies of your old JavaScript stay in caches and archives. Our guide OpenAI API key in your frontend covers checking usage for abuse.Store the key as an Edge Function secret
With the Supabase CLI, runsupabase secrets set OPENAI_API_KEY=sk-…, or open Edge Function Secrets in the Supabase dashboard and add it there. Supabase's docs say deployed functions see a new secret right away, without a redeploy, and that only the project's Owner or Administrator can create or delete secrets. Secret names can't start withSUPABASE_. For local testing, put the key insupabase/functions/.envand add that file to.gitignore. Never put the key in aVITE_,NEXT_PUBLIC_orEXPO_PUBLIC_variable.Write the function
Create it withsupabase functions new ask-ai, which makessupabase/functions/ask-ai/index.ts. The example useswithSupabasefrom Supabase's@supabase/serverpackage (public beta since May 2026), which checks the caller and handles CORS before your code runs. It accepts only a question, keeps the model, instructions andmax_output_tokenson the server, calls OpenAI's Responses API and returns only the answer:
Set// supabase/functions/ask-ai/index.ts import { withSupabase } from 'npm:@supabase/server@1' const OPENAI_API_KEY = Deno.env.get('OPENAI_API_KEY') const MODEL = Deno.env.get('OPENAI_MODEL') // a model id from OpenAI's docs export default { // auth: 'user' = only signed-in users of your app; the handler doesn't run otherwise fetch: withSupabase({ auth: 'user' }, async (req, ctx) => { if (req.method !== 'POST') { return Response.json({ error: 'Use POST' }, { status: 405 }) } const body = await req.json().catch(() => null) const question = typeof body?.question === 'string' ? body.question.trim() : '' if (!question || question.length > 2000) { return Response.json({ error: 'Send a question of 1 to 2000 characters' }, { status: 400 }) } const res = await fetch('https://api.openai.com/v1/responses', { method: 'POST', headers: { Authorization: `Bearer ${OPENAI_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: MODEL, instructions: 'You are the help assistant for my app. Answer briefly.', input: question, max_output_tokens: 500, }), }) if (!res.ok) { console.error('OpenAI error', res.status, await res.text()) return Response.json({ error: 'The AI service is unavailable' }, { status: 502 }) } const data = await res.json() const answer = (data.output ?? []) .filter((item) => item.type === 'message') .flatMap((item) => item.content) .filter((part) => part.type === 'output_text') .map((part) => part.text) .join('') return Response.json({ answer }) }), }OPENAI_MODELas a second secret (or write the model id in the code), choosing a current model from OpenAI's docs. Deploy withsupabase functions deploy ask-ai; it's then athttps://<project-ref>.supabase.co/functions/v1/ask-ai.Keep JWT verification on
Edge Functions verify the caller's JWT by default (verify_jwt = true), and Supabase recommends leaving that on for functions your users call. Supabase's own OpenAI example serves and deploys with--no-verify-jwtand doesn't check who's calling; that's fine for a quick demo, but on a live app it lets anyone call the function, which Supabase's configuration docs warn about. Turn verification off only for webhooks and other callers that can't send a user token, and then check them another way (for example a webhook signature).auth: 'user'in the code adds the same check inside the function. The publishable or anon key is not protection: it's public by design.Call it from your app
Replace the direct call toapi.openai.com(and anydangerouslyAllowBrowser: true) withsupabase.functions.invoke. Supabase's client libraries add the signed-in user's token to the request for you:
If the browser shows a CORS error and you wrote the function without// In your frontend: the signed-in user's session is sent for you const { data, error } = await supabase.functions.invoke('ask-ai', { body: { question }, }) if (error) { showMessage('Sorry, that didn\'t work. Try again in a minute.') } else { showAnswer(data.answer) }withSupabase, answer theOPTIONSpreflight request and add CORS headers to every response; Supabase's CORS docs recommend importingcorsHeadersfromnpm:@supabase/supabase-js@^2/cors(supabase-js 2.95.0 or later).Limit what one user, or a leak, can cost
Signed-in only isn't a limit by itself: anyone can sign up. Add a per-user limit in the function; Supabase's rate-limiting example uses Upstash Redis and can key the limit on the Supabase Auth user id (ctx.userClaims?.idin the code above). Then, in your OpenAI project's settings under Limits, set a monthly spend limit and turn on Enforce a hard limit. OpenAI's docs say alerts alone don't stop traffic, that requests fail with a 429 once a hard limit is hit, and that enforcement isn't instant, so spend can go slightly over.
Or ask your AI tool to do it
Paste this into Lovable, Bolt, Cursor, Claude Code or whichever tool built your app. Review what it changes before you deploy.
My app calls the OpenAI API from the browser (or has the OpenAI key in a VITE_ / NEXT_PUBLIC_ variable). Move every OpenAI call into a Supabase Edge Function. Read the key with Deno.env.get('OPENAI_API_KEY') from an Edge Function secret (tell me the exact supabase secrets set command to run; never write the key into code or any client variable). Keep JWT verification on and only accept signed-in users (withSupabase({ auth: 'user' }) from npm:@supabase/server@1, or verify the user's JWT yourself). Keep the model, instructions/system prompt and max_output_tokens on the server, accept only the inputs the feature needs with a length limit, and return only the text the UI shows. Add a per-user rate limit. Update the frontend to use supabase.functions.invoke instead of calling api.openai.com, remove dangerouslyAllowBrowser and the key from all client code, and handle CORS. List every file you changed.How this happens
Lovable, Bolt and similar builders make an AI feature work as fast as possible, and the fastest way is to call OpenAI straight from the page. The OpenAI SDK blocks that in a browser unless you set dangerouslyAllowBrowser: true, and asking the AI tool to fix the error often does exactly that. Or the key goes into a VITE_ variable because a plain one came out empty in the browser. When someone does move the call into an Edge Function, the demo code they copy often has JWT verification turned off, so the key is hidden but the function is open to everyone.
Check that it's really fixed
After you deploy, run the free check. It reads your live site the way an attacker would and tells you if any secret key is still visible.
Topic check: Exposed API key checker
Find the other leaks before someone else does
The free check reads your home page and its scripts. The website security report goes through up to 30 pages and 40 JavaScript files, plus .env and .git files, security headers, cookies and CORS, domain and email records, and libraries with known vulnerabilities. Every finding comes with the fix for your host and a prompt for your AI tool.
$19 once, including 20 runs over 30 days so you can fix things and check again.

Questions
Isn't the function protected by my Supabase anon or publishable key?
No. Those keys are meant to be public and are in your frontend for anyone to copy. A function that accepts any request carrying them is open to the whole internet. Accept only signed-in users (the default verify_jwt = true, plus auth: 'user' with withSupabase), then add a per-user limit.
Why does Supabase's own OpenAI example turn off JWT verification?
It's a minimal demo you call with curl from your own machine. Supabase's configuration docs warn that turning verification off "will allow anyone to invoke your Edge Function without a valid JWT", and the auth docs recommend leaving it on for user-facing functions. Keep it on in a live app.
Do I need to redeploy after setting the secret?
Not for deployed functions: Supabase's docs say they read a new secret immediately. Locally, restart the stack or serve the function with --env-file supabase/functions/.env.
I get a CORS error when calling the function from my site.
Browsers send an OPTIONS preflight request first. withSupabase answers it for you; if you wrote a plain Deno.serve function, return the CORS headers on the OPTIONS request and on every response. Don't switch the call to go straight to OpenAI to get around it.
Can I keep my system prompt secret this way?
Yes, if it lives only in the function. A system prompt in your frontend code is readable by anyone, the same as a key.
How do I know my app no longer calls OpenAI from the browser?
Run the free check on your live site: it flags OpenAI keys in your page and JavaScript files. The $19 report goes further, flagging direct calls to OpenAI, Anthropic, Gemini and other AI APIs from the browser, the dangerouslyAllowBrowser option and system prompts visible in your code, even when no key is showing.
Sources
- Supabase: Edge Functions environment variables (secrets)
- Supabase: Securing Edge Functions (verify_jwt, withSupabase auth modes)
- Supabase: Function configuration (verify_jwt, --no-verify-jwt warning)
- Supabase: CORS for invoking from the browser
- Supabase: Edge Functions quickstart (new, deploy, URL)
- Supabase: functions.invoke() reference
- Supabase: Rate limiting Edge Functions
- Supabase: OpenAI example (uses --no-verify-jwt)
- Supabase blog: Introducing @supabase/server (May 6, 2026, public beta)
- OpenAI API reference: Authentication and API key safety
- OpenAI API reference: Create a response
- OpenAI: Spend limits (hard limits)
- OpenAI Node SDK: browser support off by default (dangerouslyAllowBrowser)