Short answer
Never call OpenAI or Anthropic straight from the browser: anything in your frontend, including VITE_ variables, can be copied. Put the provider key in Edge Function secrets and call the model from a small proxy that checks the signed-in user, enforces a per-user quota, caps input size, fixes the model and max_tokens on the server, and never returns the key. Then set a hard spend limit at the provider as the last line of defence.
Ask an AI about this page:ChatGPTClaude
On this page
Key takeaways
- An AI provider key in your frontend is a blank cheque.
VITE_variables count as frontend. - Call the model from an Edge Function that reads the key from secrets and never sends it back.
- The proxy checks four things before it spends money: who is calling, how often, how much input, and which model with how many output tokens (fixed on the server).
- Set a hard spend limit at OpenAI or Anthropic, per project or workspace, as the last line.
- Use a separate key per app and environment, so you can rotate one without breaking the others.
Why the key must never reach the browser
Many first versions of AI features look like this: the React app imports the OpenAI or Anthropic SDK, reads the key from import.meta.env.VITE_OPENAI_API_KEY and calls the model directly. It works in the preview, so it ships.
The problem is in Vite’s own documentation: variables prefixed with VITE_ are “exposed in client-side source code after Vite bundling”, and they should not hold API keys. Anyone can open your site, search the JavaScript for the key and use it from their own scripts. OpenAI’s key safety guide says the same in plain words: never deploy a key in browsers or mobile apps, and route requests through your own backend. A leaked key costs you money until you notice and rotate it, and it can also burn through rate limits shared with your other apps.
A second, quieter version of the same leak: an Edge Function that returns the key to the browser, for example a get-config function that hands the frontend everything it needs to call the model itself. The key never appears in your bundle, but anyone who calls the function gets it. Both cases are described in the fix for AI keys in client code.
The shape of a safe setup
The browser never talks to the AI provider. It talks to your Edge Function, and only the function holds the key:
Browser
Sends the user’s text and the Supabase session token to /functions/v1/ai-summary. No provider key, no model name, no token limit.
Edge Function
Verifies the token, checks the per-user quota, checks the input size, then calls the provider with a model and max_tokens that are fixed in code. Returns only the answer.
Provider
Bills the project or workspace the key belongs to. A hard spend limit there stops the damage if everything above fails.
The proxy, line by line
This is a complete Supabase Edge Function. It uses Supabase’s @supabase/server package, which verifies the caller’s token before your handler runs, and the official Anthropic SDK. For OpenAI, the structure is the same; only the client and the call change.
import Anthropic from "npm:@anthropic-ai/sdk@1";
import { withSupabase } from "npm:@supabase/server@1";
// The key comes from Edge Function secrets and never leaves the server.
const anthropic = new Anthropic({ apiKey: Deno.env.get("ANTHROPIC_API_KEY") });
// Fixed on the server: the browser cannot pick a bigger model or a longer answer.
const MODEL = "claude-opus-5-5";
const MAX_OUTPUT_TOKENS = 2048;
const MAX_INPUT_CHARS = 4000;
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const userId = ctx.userClaims?.id;
if (!userId) return Response.json({ error: "Not signed in" }, { status: 401 });
const body = await req.json().catch(() => null);
const text = typeof body?.text === "string" ? body.text.trim() : "";
if (!text || text.length > MAX_INPUT_CHARS) {
return Response.json({ error: `Send between 1 and ${MAX_INPUT_CHARS} characters.` }, { status: 400 });
}
// Per-user daily quota (check_rate_limit is defined in the rate limiting guide).
const { data: allowed, error } = await ctx.supabaseAdmin.rpc("check_rate_limit", {
_key: `ai-day:${userId}`,
_max_hits: 50,
_window: "1 day",
});
if (error) return Response.json({ error: "Please try again later." }, { status: 503 });
if (!allowed) return Response.json({ error: "Daily limit reached." }, { status: 429 });
try {
const message = await anthropic.messages.create({
model: MODEL,
max_tokens: MAX_OUTPUT_TOKENS,
system: "Summarise the user's text in three short bullet points.",
messages: [{ role: "user", content: text }],
});
const summary = message.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("\n");
return Response.json({ summary });
} catch (err) {
// Log the status, not the user's text or the key.
console.error("AI provider error", err instanceof Anthropic.APIError ? err.status : "network");
return Response.json({ error: "The assistant is not available right now." }, { status: 502 });
}
}),
};What each guard does:
withSupabase with auth: "user"rejects requests without a valid user token. Supabase’s docs recommend keepingverify_jwton for user-facing functions, so the platform checks the token as well. The user ID comes from the verified token, never from the request body.- The input cap stops someone from sending a whole book per request. OWASP’s LLM Top 10 lists oversized inputs as one way to drive up cost.
- The quota uses the tested Postgres counter from the rate limiting guide. Here it allows 50 summaries per user per day; add a per-minute key as well against bursts.
MODELandmax_tokenslive in the code.max_tokensis the hard ceiling for one answer, so together with the input cap it bounds the worst-case cost of a single request.- Errors return a generic message. The log line records the status code, not the prompt, which may contain personal data, and never the key.
Set the secret once with supabase secrets set ANTHROPIC_API_KEY=… or on the Edge Function Secrets page in the dashboard. Supabase’s docs note that production secrets take effect without a redeploy.
Set a hard spend limit at the provider
Your code can have bugs, and keys can leak. A spend limit at the provider caps the damage either way. What exists today (checked on 3 December 2026):
| Provider | What you can set | Where | What happens at the limit |
|---|---|---|---|
| OpenAI | Spend alerts (notify only) and hard spend limits for the organization, a project or a single API key | Project settings → Limits → Spend → turn on “Enforce a hard limit” | Requests return 429 with an error code such as project_spend_limit_exceeded |
| Anthropic | Your own monthly organization spend limit below your tier’s cap, plus spend and rate limits per workspace | Claude Console → Spend limits; per workspace on the Workspaces page | Requests are refused with an error that says when access resumes |
Two details from the providers’ documentation matter in practice. First, OpenAI’s spend alerts only notify; only a hard limit stops traffic, and OpenAI notes that enforcement “is not instantaneous”, so spend can slightly exceed the limit. Second, Anthropic’s spend limit on the default workspace might not count all usage, so put your app’s key in its own workspace and limit that.
Size the limit to what a bad day may cost, not to your expected usage. If your app normally spends 40 a month, a hard cap of 100 leaves room for growth and still stops a runaway loop on day one. The fix No AI spend cap walks through it step by step.
One key per app and environment
Give every app, and ideally every environment, its own key in its own OpenAI project or Anthropic workspace:
- A leaked preview key can be revoked without taking production down.
- Spend limits and usage graphs show which app is burning money.
- OpenAI’s key safety guide also recommends expiry dates and regular rotation; see secret rotation for the order of steps.
A fix prompt for your AI builder
Find every place in this project where the frontend calls OpenAI, Anthropic or another AI provider directly, or reads an AI provider key from a VITE_ variable or from a function response.
Replace them with one Supabase Edge Function per AI feature that:
- uses withSupabase with auth: “user” from npm:@supabase/server@1 and takes the user id only from ctx.userClaims;
- reads the provider key with Deno.env.get() and never returns it;
- rejects inputs longer than 4000 characters;
- calls public.check_rate_limit with ctx.supabaseAdmin for a daily per-user quota and returns 429 when it is used up;
- fixes the model and max_tokens as constants in the function;
- logs only status codes, never prompts or keys.
Remove the VITE_ AI key variables and the provider SDK from the frontend. Tell me which keys I must rotate because they were in the browser bundle.
Checklist
AI API safety checklist
0/9 done
Your progress is saved in this browser only.
Frequently asked questions
Is a VITE_ environment variable a safe place for my OpenAI key?
No. Vite’s documentation says variables with the VITE_ prefix end up in the client-side code after bundling and should not contain API keys. Anyone can read them in the browser. Store the key as an Edge Function secret instead.
Do provider spend limits stop usage the moment I hit them?
Not to the cent. OpenAI’s documentation says enforcement is not instantaneous, so recorded spend can slightly exceed a hard limit. Treat a spend limit as the last line of defence and keep your own per-user quotas in front of it.
My Edge Function needs auth anyway. Why add a quota?
Because sign-up is usually free. Authentication tells you who is calling, not how often. Without a quota, one free account, or a script that creates many, can call your AI endpoint thousands of times on your bill.
Should the browser choose the model or max_tokens?
No. If the request body decides the model or the answer length, anyone can ask for the most expensive model and the longest answer. Fix both in the server code, and if you offer choices, map a short allowed value like ‘fast’ or ‘smart’ to a model on the server.
Sources
- 1.Best Practices for API Key Safety — OpenAI Help Center
- 2.Spend limits — OpenAI Docs
- 3.Rate limits and spend limits — Anthropic Docs
- 4.Environment variables (secrets) — Supabase Docs
- 5.Securing Edge Functions — Supabase Docs
- 6.Env variables and modes — Vite Docs
- 7.LLM10:2025 Unbounded Consumption — OWASP Top 10 for LLM Applications