14 min read · Updated 2026-11-30
Lovable Supabase Edge Function: keep the API key off the client
Store an OpenAI, Anthropic, or Gemini key as a Supabase secret and call the model from an Edge Function, so a Lovable app's built JavaScript never contains it.
Steps
- Put the provider key in a Supabase secret. Save it with supabase secrets set OPENAI_API_KEY=... or in the dashboard under Edge Function Secrets. Keep that value out of git, and do not give the variable a VITE_ or NEXT_PUBLIC_ name.
- Read the secret inside a Deno Edge Function. The function reads the key with Deno.env.get("OPENAI_API_KEY"). The browser never receives that value.
- Call the model with fetch and a token cap. The function calls the provider with fetch. For OpenAI Chat Completions, set max_completion_tokens and trim the user message. The client does not call api.openai.com.
- Require a signed-in user and a daily cap. Leave verify_jwt at its default of true. Skip --no-verify-jwt, and do not set verify_jwt = false. Inside the function, require a user from the Authorization bearer token, and reserve one call per user per day in Postgres before the model request.
- Handle CORS and invoke the function from the client. Answer the OPTIONS preflight and send CORS headers on every response. After sign-in, the Lovable app calls supabase.functions.invoke with the message in the body.
- Rotate a leaked key and scan the live site. If the key was ever in frontend code or git history, revoke it and store only the new one as the secret. Search the built JavaScript for sk-, then run the BrakeKey scan on the public URL.
Lovable ships a Vite app. The visitor's browser downloads the JavaScript Vite emits. When client code reads import.meta.env.VITE_SOMETHING, Vite pastes that value into those files at build time. A provider key in a VITE_ variable is in the bundle. A key written as a plain string in a component is in the bundle too. Anyone who can load the site can copy it and call the model as you.
The Supabase key in that same bundle is a different object. The legacy anon key, and the current publishable key, are designed to be public, with Row Level Security behind them. An OpenAI, Anthropic, or Gemini key bills your account the moment someone else uses it. The fix is to keep the provider key in a Supabase Edge Function secret and to make the browser call that function.
Why the built files are the source of truth
Vite's rule is the prefix. Variables whose names start with VITE_ are the ones client code is allowed to read, and the build replaces each reference with the literal value. Search the emitted JavaScript, usually under dist/assets, for sk-. Also search the scripts the deployed site actually serves. The Lovable editor can look clean while the last deploy is still carrying the key.
- sk- and sk-proj- are OpenAI key prefixes. sk-ant- is Anthropic. AIza is the prefix on a Google AI Studio key used for Gemini.
- A variable named VITE_OPENAI_API_KEY, VITE_ANTHROPIC_API_KEY, or VITE_GEMINI_API_KEY is a client variable. So is NEXT_PUBLIC_ if a file uses that prefix.
- The publishable Supabase key in the bundle is expected. The provider key next to it is the leak.
1. Store the key as a Supabase secret
Production Edge Functions read secrets you set in the dashboard or with the CLI. In the dashboard, open Edge Function Secrets, enter the key name and the value, and save. Creating or deleting a production secret requires the Owner or Administrator role. With the CLI, from the project directory:
supabase secrets set OPENAI_API_KEY=your-key-hereThat command works, and it also lands in your shell history. Prefer the dashboard, or a gitignored file, when the value is a real key. supabase secrets set --env-file .env pushes every secret in that file, so the file should contain only what you mean to upload. Add the file to .gitignore before you commit. Locally, the function reads supabase/functions/.env when the stack starts. Gitignore that file too. A .env.example with empty names does not supply the value.
2. Read it with Deno.env.get, then call the model
The function below is Deno and TypeScript, which is the Edge Function runtime. It reads OPENAI_API_KEY with Deno.env.get. It never returns that string to the browser. Replace YOUR_MODEL_ID with a model id your OpenAI key is allowed to call. The sample refuses to send a request until you do. max_completion_tokens is the Chat Completions field that caps one reply, including reasoning tokens on models that use them. OpenAI marks the older max_tokens field as deprecated, and o-series models reject it.
DAILY_CAP of 20 and a 4,000-character message trim are example limits for a hobby app, not platform defaults. Pick numbers you can afford. The cap counts calls. The token field caps one completion. Input tokens still cost money, which is why the message is trimmed before the call.
Hosted functions inject SUPABASE_URL. Older projects also inject SUPABASE_ANON_KEY and SUPABASE_SERVICE_ROLE_KEY. Current projects inject SUPABASE_PUBLISHABLE_KEYS and SUPABASE_SECRET_KEYS as JSON objects, and the key you want is the default entry. The helper below accepts either shape. The secret key bypasses Row Level Security. It stays in the function and is used only to spend quota. The publishable key is the one that may also exist in the browser.
import { createClient } from "npm:@supabase/supabase-js@2";
const DAILY_CAP = 20;
const MAX_COMPLETION_TOKENS = 400;
const OPENAI_MODEL = "YOUR_MODEL_ID";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type, x-retry-count, traceparent, tracestate, baggage",
"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
};
function json(body: unknown, status = 200) {
return Response.json(body, { status, headers: corsHeaders });
}
function keyFrom(legacyName: string, jsonName: string): string | undefined {
const legacy = Deno.env.get(legacyName);
if (legacy) return legacy;
const raw = Deno.env.get(jsonName);
if (!raw) return undefined;
try {
const parsed = JSON.parse(raw) as { default?: string };
return parsed.default;
} catch {
return undefined;
}
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
if (req.method !== "POST") return json({ error: "Method not allowed." }, 405);
const supabaseUrl = Deno.env.get("SUPABASE_URL");
const publishable = keyFrom("SUPABASE_ANON_KEY", "SUPABASE_PUBLISHABLE_KEYS");
const secret = keyFrom("SUPABASE_SERVICE_ROLE_KEY", "SUPABASE_SECRET_KEYS");
const openaiKey = Deno.env.get("OPENAI_API_KEY");
if (
!supabaseUrl ||
!publishable ||
!secret ||
!openaiKey ||
OPENAI_MODEL === "YOUR_MODEL_ID"
) {
return json({ error: "Server is missing a secret or the model id." }, 500);
}
const header = req.headers.get("Authorization") ?? "";
const token = header.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : "";
if (!token) return json({ error: "Sign in first." }, 401);
const userClient = createClient(supabaseUrl, publishable, {
global: { headers: { Authorization: header } },
});
const { data: userData, error: userError } = await userClient.auth.getUser(token);
if (userError || !userData.user) {
return json({ error: "Sign in first." }, 401);
}
let message = "";
try {
const body = await req.json();
message = String(body?.message ?? "").trim().slice(0, 4000);
} catch {
message = "";
}
if (!message) return json({ error: "Send a message." }, 400);
const admin = createClient(supabaseUrl, secret);
const { data: allowed, error: quotaError } = await admin.rpc("reserve_ai_call", {
uid: userData.user.id,
cap: DAILY_CAP,
});
if (quotaError) return json({ error: "Could not check today's limit." }, 500);
if (!allowed) return json({ error: "Daily AI limit reached." }, 429);
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: OPENAI_MODEL,
messages: [{ role: "user", content: message }],
max_completion_tokens: MAX_COMPLETION_TOKENS,
}),
});
if (!ai.ok) return json({ error: "The model request failed." }, 502);
const payload = await ai.json();
const text = payload?.choices?.[0]?.message?.content ?? "";
return json({ text });
});On supabase-js 2.95 and later you can import corsHeaders from npm:@supabase/supabase-js@^2/cors instead of pasting the object, so the allow-list stays aligned with the headers the client sends. The object above matches the list Supabase documents for browser calls, including the trace headers added by 2.112.3. Access-Control-Allow-Origin: * is the example Supabase publishes. The function still requires a user token, so another website that can make the browser send the request still cannot spend the key without a signed-in user.
If the wrapper withSupabase from npm:@supabase/server is what your project uses, it answers the OPTIONS preflight for you, and auth: "user" is the mode that requires a user JWT. The secret is still Deno.env.get("OPENAI_API_KEY"), the model call is still fetch, and verify_jwt stays on. The sample above is the self-contained Deno.serve form.
Anthropic and Gemini use the same shape
Keep those keys in secrets too: ANTHROPIC_API_KEY or GEMINI_API_KEY, read with Deno.env.get. The browser still calls only your function. Anthropic's Messages API is POST https://api.anthropic.com/v1/messages. Send the key as Authorization: Bearer, or as the legacy x-api-key header. The anthropic-version header is required (current docs use 2026-10-21). The body requires max_tokens, which is Anthropic's own field and the cap for that reply. A key that is not scoped to one workspace also needs the anthropic-workspace-id header. For Gemini, the function calls generativelanguage.googleapis.com and attaches the key on the server. The browser never puts an AIza key in a query string.
3. Reserve one call per user before you spend
A hidden key with a public function URL still sends you the bill. A counter in the function's memory is not a cap: each request can run in a fresh isolate, and two requests at once will not see each other. Store the count in Postgres and increment it in one statement. Run this in the SQL editor. The rate-limit guide on this site uses this same reserve_ai_call function and explains the statement at more length. No policy is added for the browser roles. With row level security on and no policy, anon and authenticated cannot read the table. The function is security definer, and only service_role may execute it.
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 insert adds the first call of the day. The update adds one only while the row is still under the cap, and it does that in the same statement, so two overlapping calls cannot both pass a check they each read as "still under." When the row is already at the cap, the update changes nothing, the function returns false, and the Edge Function returns 429 without calling the model. A failed model request still consumes the reserved call. That is the conservative direction.
4. Leave JWT verification on
verify_jwt defaults to true. The platform checks the request before your code runs. Deploy with supabase functions deploy openai-chat and do not add --no-verify-jwt. That flag overrides the config and turns the check off. In supabase/config.toml, do not set verify_jwt = false for this function. The same flag exists on supabase functions serve for local webhooks. Do not serve this function that way.
[functions.openai-chat]
verify_jwt = true5. Call the function from the Lovable app
Use the Supabase client the app already has, after the user has a session. supabase-js JSON-encodes an object body. It sends the session access token on Authorization and the project key on apikey. If you pass your own Authorization header into invoke, that header replaces the session token, so leave it unset.
const { data, error } = await supabase.functions.invoke("openai-chat", {
body: { message },
});Signed out, there is no user access token to send. Your function should answer 401. The client component should not import the provider key, should not read a VITE_ provider variable, and should not fetch api.openai.com, api.anthropic.com, or generativelanguage.googleapis.com.
6. Rotate anything that already leaked
If the provider key was in a component, a VITE_ variable, a Lovable chat, or a git commit, treat it as copied. Revoke it in the provider's dashboard and create a replacement. The replacement goes only in the Supabase secret. Removing the string from the latest file does not remove it from history or from anyone who already saved it. Revoking is what stops the meter. Then set a hard monthly spend limit at the provider, with enforcement turned on, so a missed copy has a ceiling. The spending-limit guide and the leaked-key guide on this site cover that checklist.
Paste this into Lovable
Paste this into Lovable
This is a Lovable app. Move the OpenAI, Anthropic, or Gemini call off the client and into a Supabase Edge Function named openai-chat.
Requirements:
- Delete the provider key from every file the browser downloads, including strings in components and any variable whose name starts with VITE_ or NEXT_PUBLIC_.
- I will save the key myself as a Supabase secret (supabase secrets set OPENAI_API_KEY=... or Edge Function Secrets). The function reads it with Deno.env.get. Do not print it, and do not invent a key in code.
- The function is Deno/TypeScript. It calls the provider with fetch. The browser calls supabase.functions.invoke("openai-chat", { body: { message } }) and never calls api.openai.com, api.anthropic.com, or generativelanguage.googleapis.com.
- Handle CORS. Answer OPTIONS, and send CORS headers on every response.
- Leave verify_jwt at the default true. Do not deploy with --no-verify-jwt and do not set verify_jwt = false.
- Require a signed-in user: read the bearer token and reject the request when auth.getUser(token) returns no user. The publishable key is not a user.
- Before calling the model, reserve one call for that user id in Postgres with an atomic increment, and return 429 when the daily cap is reached.
- Cap the completion (OpenAI: max_completion_tokens) and trim the user message.
- Do not send a test prompt to the provider.How you know it worked
- Search the built JavaScript for sk-. In a Vite build that is the files under dist/assets. On the deployed site, open the script URLs the page loads and search those too. Also search for sk-ant- and AIza.
- Send one chat message while signed in. The request URL should be your project's /functions/v1/openai-chat. It should not be api.openai.com, api.anthropic.com, or generativelanguage.googleapis.com.
- Sign out and try the call again. You want a 401, from your function or from the gateway, and no model response.
- Run the free BrakeKey scan on the public URL. The scanner reads the public page and the same-site scripts. A provider key still in the bundle shows up as a finding. The scan does not call your function and cannot see a secret stored in Supabase.
Questions
If my Lovable app reads a VITE_ key in only one file, is the value still public?
Yes, once client code reads it. Vite writes every VITE_ value that client code references into the JavaScript files the browser downloads. A key typed as a string in a component lands in those same files. The check is the built output, and the live scripts, not the editor.
Does verify_jwt mean only signed-in users can spend the provider key?
Leave it on. The default is true, and an AI function should stay there: do not deploy with --no-verify-jwt, and do not set verify_jwt = false. That platform check is not the whole lock. For compatibility it also accepts a publishable or secret API key, including on the apikey header, and the publishable key is already in the Lovable app. Inside the function, call getUser with the bearer token and refuse the request when there is no user. Count calls against that user id.
Do I redeploy the function after supabase secrets set?
The running function reads a new secret immediately, so the value alone does not need a redeploy. Deploy when the function code changes. A secret name cannot start with SUPABASE_. That prefix is reserved, and the dashboard and Management API reject it.
Will max_completion_tokens stop a surprise bill by itself?
It caps the tokens of one OpenAI Chat Completions response, including reasoning tokens on models that use them. It does not cap how many times the function is called, and the input still costs money until you trim what you send. OpenAI marks max_tokens as deprecated, and o-series models reject it, so set max_completion_tokens. Pair that with a per-user daily cap and a hard spend limit on the OpenAI organization.
The Supabase anon key is already in my Lovable app. Is that the same leak?
The legacy anon key, and the current publishable key, are meant to ship in the browser. Row Level Security is what keeps that safe. An OpenAI, Anthropic, or Gemini key has nothing like that in front of it. Whoever copies the provider key spends your account.
I already committed the key. Is deleting the file enough?
Revoke the key at the provider. Deleting the latest file leaves the value in git history and in any clone that already pulled it. Put only the replacement in the Supabase secret. Cleaning history matters so a later deploy does not ship the old value again. Revoking is what stops the charges.