Security
OpenAI or Stripe API key in the front end of an AI-built app: moving it to an Edge Function
If your app talks to OpenAI or Stripe directly from the browser, the secret key travels with the page, and anyone who opens it can copy the key and use it on your account. OpenAI says never to deploy a key in browsers or mobile apps, and Stripe says only publishable pk_ keys are safe to expose. The fix is to move the call into a server function, such as a Supabase Edge Function, that keeps the key in its secrets, checks who is calling, and limits how often they can call. Then replace the exposed key.
What you are seeing
The problem is invisible while the app works, so you usually find out from one of these:
- An OpenAI bill or usage graph far above what your users could have produced, or requests to models your app does not use.
- Activity in your Stripe account that your app did not start: customers, refunds or payment links you do not recognise.
- Lovable's Deep scan reports leaked secrets or credentials in your source code (Lovable security), or GitHub flags a secret in your repository.
- The AI feature or checkout in your app works, but there is no
supabase/functionsfolder or other server code anywhere in the project. - The OpenAI library in your code has the option
dangerouslyAllowBrowser: true. The library refuses to run in a browser without it, because running there "exposes your secret API credentials in the client-side code" (openai-node README).
pk_test_..., pk_live_...) is meant for front-end code (Stripe API keys), and so is the Supabase publishable or anon key. The ones that must never ship are Stripe secret (sk_) and restricted (rk_) keys, OpenAI API keys, and the Supabase secret or service_role key - for that last one, see our service_role guide.How to check it yourself
Check your own project only. All of this is read-only.
1. Watch what the browser sends
- Open your live app in Chrome, press F12 (Cmd+Option+I on a Mac) and go to the Network tab.
- Type
openaiin the filter box, then use the AI feature. A request that goes straight toapi.openai.comfrom the browser (other than a Realtime session started with a short-lived key your server created) means the API key is in the browser. A request to your own function (for example a URL containing/functions/v1/) is the safe pattern. - Clear the filter, type
stripe, and start a checkout. Click each request toapi.stripe.comand look through Headers and Payload. A value starting withpk_is the publishable key and is expected. A value starting withsk_orrk_means a secret key is in the browser.
2. Search the code and the build output
If your project is synced to GitHub, clone it and run this from the project folder after npm run build, so it also covers what actually ships to the browser:
grep -rnoE "sk_(live|test)_[A-Za-z0-9]+|rk_(live|test)_[A-Za-z0-9]+|api\.openai\.com|api\.stripe\.com|dangerouslyAllowBrowser" \
--exclude-dir=node_modules --exclude-dir=.git .supabase/functions/ are server code and fine, as long as the key is read from a secret there and not written into the file. Any match in front-end code or in the build folder (dist, .output, .next or similar) is the problem.Then look at the names of your environment variables. Some prefixes mean "put this in the browser":
grep -rnE "(VITE_|NEXT_PUBLIC_)[A-Z0-9_]*(OPENAI|STRIPE|SECRET|API_KEY|TOKEN)" \
--exclude-dir=node_modules --exclude-dir=.git .- Vite (Lovable projects created before 2026-05-13, Bolt and many others): "Variables prefixed with
VITE_will be exposed in client-side source code after Vite bundling", and Vite says they should not contain API keys (Vite env variables). - Next.js: a
NEXT_PUBLIC_variable is inlined at build time into the JavaScript sent to the browser; variables without the prefix stay on the server (Next.js environment variables). - Bolt: environment variables can be read by code running in the browser; only values saved as Secrets are kept to server functions (Bolt secrets).
- A key in a mobile app built with Capacitor or Expo is in the same position as a key in a web page: OpenAI's guidance names "browsers or mobile apps" together (OpenAI key safety).
3. Check the Git history
git log --all --oneline -S "sk_live_"
git log --all --oneline -S "rk_live_"
git log --all --oneline -S "dangerouslyAllowBrowser"4. Look for use you did not cause
- OpenAI: open the Usage page in your OpenAI dashboard and compare it with what your app does (OpenAI key safety).
- Stripe: on the API keys page, open the menu (⋯) next to the exposed key and choose View request logs. It shows every request made with that key (Stripe API keys). Look for requests your app never makes.
Why it happens
Everything in a web page's JavaScript is downloaded by every visitor. There is no way to hide a value in it. Lovable's docs put it plainly: "Secrets stored in frontend code are visible to users and should be considered compromised" (Lovable docs).
AI builders start with a front-end app. Asked to "add ChatGPT" or "add Stripe checkout", the shortest path to a working feature is to call the outside service directly from the page, with the key in a variable or written into the file. It works on the first try, which is why it is easy to miss. What should happen instead is a small piece of server code between the page and the service: OpenAI says requests "should _always_ be routed through your own backend server where you can keep your API key secure" (OpenAI key safety).
What someone can do with the key depends on the key:
- OpenAI API key: make requests on your account, so you pay for them. OpenAI notes that spend alerts alone do not stop API traffic.
- Stripe secret key (
sk_): Stripe describes it as having unrestricted permissions on all Stripe APIs - a bad actor "can do anything in your account" (Restricted API keys). - Stripe restricted key (
rk_): whatever permissions you gave it. Stripe still says to treat it with the same caution as a secret key.
How to fix it
Otherwise, build the server side first, then switch the app over, then retire the old key. The examples use Supabase Edge Functions, which is what Lovable builds on; other platforms have their own server functions and the steps are the same.
1. Create new keys with the least power possible
- OpenAI: create a new key inside a project (Organization settings > your project > API Keys). Each project has its own keys, and a project key is limited to that project (OpenAI projects). Under the project's Limits, set a monthly spend limit and turn on Enforce a hard limit - OpenAI recommends this to limit unexpected costs from a leaked key, and notes that enforcement is not instant, so spending can slightly exceed the limit.
- Stripe: create a restricted key (API keys > Create restricted key) with only the permissions your server code needs. Stripe recommends restricted keys over secret keys and shows how to work out the permissions from the old key's request logs (Restricted API keys). Do it in a sandbox first, then create the matching live key.
- Do not paste the new key into the AI chat or into any file. It goes straight into secrets in the next step.
2. Store the keys as Edge Function secrets
- Your own Supabase project: in the dashboard open Edge Functions > Secrets, or use the CLI as below. A function reads a new secret immediately, without a redeploy, and secret names cannot start with
SUPABASE_(Edge Function secrets). - Lovable: More > Settings > Secrets. Lovable says secrets are encrypted, injected into your Edge Functions and never reach the browser; with your own Supabase connected, they are managed in Supabase (Lovable secrets). Lovable's Stripe integration stores the key as a backend secret named
STRIPE_SECRET_KEYand accepts a restricted key (Lovable Stripe). - Bolt: the database icon in the top menu > Secrets (Bolt secrets).
supabase secrets set OPENAI_API_KEY=your-new-openai-key
supabase secrets set OPENAI_MODEL=the-model-your-app-uses
supabase secrets set STRIPE_SECRET_KEY=rk_live_your-new-restricted-key
supabase secrets set STRIPE_PRICE_PRO=price_your-price-id
supabase secrets set SITE_URL=https://your-app.example.com
supabase secrets listsupabase/functions/.env, which must be in .gitignore. Never put these values in the front end's .env file. Typing a key on the command line saves it in your shell history. For live keys, prefer the dashboard (Edge Functions > Secrets), or put a space before the command if your shell is set to leave such lines out of its history.3. Add a per-user limit in the database
Moving the key to the server stops people copying it, but anyone who can call your function can still spend your OpenAI budget through it. A small counter per user and day caps that. Run this in the SQL Editor or put it in a migration:
create table public.ai_usage (
user_id uuid not null references auth.users (id) on delete cascade,
day date not null default current_date,
requests integer not null default 0,
primary key (user_id, day)
);
alter table public.ai_usage enable row level security;
-- No policies on purpose: only server code using the secret key touches this table.
revoke all on table public.ai_usage from anon, authenticated;
grant select, insert, update on table public.ai_usage to service_role;
-- Adds one request and returns true, or returns null once the limit is reached.
create or replace function public.bump_ai_usage(p_user_id uuid, p_limit integer)
returns boolean
language sql
security invoker
set search_path = ''
as $$
insert into public.ai_usage as u (user_id, day, requests)
values (p_user_id, current_date, 1)
on conflict (user_id, day)
do update set requests = u.requests + 1
where u.requests < p_limit
returning true;
$$;
revoke execute on function public.bump_ai_usage(uuid, integer) from public, anon, authenticated;
grant execute on function public.bump_ai_usage(uuid, integer) to service_role;where stops the update and no row is returned (PostgreSQL INSERT), so the function returns null (SQL functions). Functions are executable by everyone by default (PostgreSQL privileges), hence the revoke. The explicit grant to service_role matters since Supabase stopped granting access to new tables automatically (changelog).4. Move the OpenAI call into an Edge Function
Create the function with supabase functions new ai-chat (Edge Functions quickstart). Supabase's withSupabase wrapper lets only signed-in users through and gives the function the caller's verified user id (Securing Edge Functions); it also adds the standard CORS headers the browser needs (@supabase/server).
// supabase/functions/ai-chat/index.ts
import OpenAI from "npm:openai@^7";
import { withSupabase } from "npm:@supabase/server@^1";
const openai = new OpenAI({ apiKey: Deno.env.get("OPENAI_API_KEY") });
const MODEL = Deno.env.get("OPENAI_MODEL");
const DAILY_LIMIT = 50; // requests per user per day - pick your own number
const MAX_PROMPT_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 });
}
if (!MODEL) {
console.error("ai-chat: OPENAI_MODEL secret is not set");
return Response.json({ error: "Not configured" }, { status: 500 });
}
let prompt: unknown;
try {
({ prompt } = await req.json());
} catch {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
if (typeof prompt !== "string" || prompt.trim() === "" || prompt.length > MAX_PROMPT_CHARS) {
return Response.json({ error: "Invalid prompt" }, { status: 400 });
}
const { data: allowed, error: limitError } = await ctx.supabaseAdmin.rpc("bump_ai_usage", {
p_user_id: userId,
p_limit: DAILY_LIMIT,
});
if (limitError) {
console.error("ai-chat: usage check failed", { userId, message: limitError.message });
return Response.json({ error: "Try again later" }, { status: 500 });
}
if (allowed !== true) {
return Response.json({ error: "Daily limit reached" }, { status: 429 });
}
try {
const response = await openai.responses.create({ model: MODEL, input: prompt });
return Response.json({ text: response.output_text });
} catch (err) {
console.error("ai-chat: OpenAI request failed", { userId, err });
return Response.json({ error: "The AI service did not answer" }, { status: 502 });
}
}),
};Deploy it with supabase functions deploy ai-chat (Lovable deploys Edge Functions for you). Supabase checks the user's token before the function runs, because verify_jwt is on by default (Securing Edge Functions).
5. Move Stripe calls the same way
For checkout, the server should decide what is being bought and for how much. Stripe's own API reference asks you to validate requests on your server and protect the endpoint that creates Checkout Sessions with access controls and limits on repeated creation (Create a Checkout Session).
// supabase/functions/create-checkout/index.ts
import Stripe from "npm:stripe@^22";
import { withSupabase } from "npm:@supabase/server@^1";
const stripe = new Stripe(Deno.env.get("STRIPE_SECRET_KEY") as string);
const SITE_URL = Deno.env.get("SITE_URL");
// The browser sends a plan name; only the server knows which Stripe price it maps to.
const PRICES = new Map([["pro", Deno.env.get("STRIPE_PRICE_PRO")]]);
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 });
}
let plan: unknown;
try {
({ plan } = await req.json());
} catch {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
const priceId = typeof plan === "string" ? PRICES.get(plan) : undefined;
if (!priceId || !SITE_URL) {
return Response.json({ error: "Unknown plan" }, { status: 400 });
}
try {
const session = await stripe.checkout.sessions.create({
mode: "payment", // "subscription" for recurring prices
line_items: [{ price: priceId, quantity: 1 }],
success_url: `${SITE_URL}/checkout/success`,
cancel_url: `${SITE_URL}/pricing`,
client_reference_id: userId,
});
return Response.json({ url: session.url });
} catch (err) {
console.error("create-checkout: Stripe request failed", { userId, err });
return Response.json({ error: "Could not start checkout" }, { status: 502 });
}
}),
};client_reference_id ties the payment to the user, so the webhook that confirms the payment knows whose account to upgrade. The webhook's signing secret is a separate value from the API key and belongs in secrets too. This example has the access control (auth: "user") but no limit on repeated session creation, which Stripe also asks for. Add a counter like the one from step 3 (a separate table, with its own lower limit) before calling stripe.checkout.sessions.create.6. Switch the front end and remove the keys
The page now calls your functions with the ordinary Supabase client. The signed-in user's session is sent along automatically:
const { data, error } = await supabase.functions.invoke("ai-chat", {
body: { prompt: userText },
});
const { data: checkout } = await supabase.functions.invoke("create-checkout", {
body: { plan: "pro" },
});
if (checkout?.url) window.location.href = checkout.url;error in the UI: a 429 from ai-chat means the user hit the daily limit, not that the app is broken. If you call a function with plain fetch instead, follow Supabase's CORS guide.- Delete the OpenAI and Stripe secret keys from every front-end file and front-end
.envfile, and removedangerouslyAllowBrowserand any direct calls toapi.openai.com. Keep the Stripe publishable key if Stripe.js uses it. - In Lovable, you can ask for this in the chat - Lovable's docs suggest a prompt along the lines of adding the key "securely without exposing it in the frontend code" (Lovable docs). Check the result with the search from the check section; do not take the AI's word for it.
- Run
npm run buildand the two searches from the check section again. Nothing outsidesupabase/functions/should match except the Stripe publishable key. - Use the AI feature and a test checkout in the live app with the Network tab open. You should see requests to
/functions/v1/ai-chatand/functions/v1/create-checkout, and none toapi.openai.comorapi.stripe.comcarrying ansk_orrk_value. - If you have a mobile app, ship an update built without the keys. Versions already installed keep the old key until you retire it.
7. Retire the exposed keys
- OpenAI: delete the old key on the API Keys page once the new setup works. OpenAI's guide says to revoke the old key after verifying that the replacement works.
- Stripe: rotate or expire the old key on the API keys page. A rotated key keeps working for up to 7 days if you choose a later expiration, which avoids downtime; Stripe suggests checking its request logs and expiring it once traffic on it has dropped to zero (Stripe API keys). For a key that was public, a short window is better than a long one.
- Removing the key from the code or from Git history does not make it safe. Anyone who copied it before still has it until it is revoked.
When to get help
- You are not sure the exposed key is the only one, or whether the app's other server code and database still trust the browser.
- Several features depend on outside services (AI, payments, email, maps) and you are not sure which keys are in the browser.
- The AI feature needs limits that depend on plans, credits or teams, and you want the checks in the Edge Function and the database done right.
- You are not sure where your keys live, or whether staging and production use separate keys and projects.
- A mobile app with the key built in is already in the store and you need to plan the update and the key rotation.
Sources
Primary documentation this guide was checked against. Platforms change - if something here no longer matches, the source wins.
- Best practices for API key safetyOpenAI Help Center
- Managing projects in the API platformOpenAI Help Center
- openai-node README: RequirementsOpenAI on GitHub
- API keysStripe docs
- Restricted API keysStripe docs
- Create a Checkout SessionStripe API reference
- Environment variables (secrets)Supabase docs
- Edge Functions quickstartSupabase docs
- Securing Edge FunctionsSupabase docs
- CORS support for Edge FunctionsSupabase docs
- @supabase/serverSupabase on GitHub
- Tables not exposed to the Data API automaticallySupabase changelog
- Query language (SQL) functionsPostgreSQL docs
- INSERTPostgreSQL docs
- PrivilegesPostgreSQL docs
- Avoiding security pitfallsLovable docs
- SecurityLovable docs
- SecretsLovable docs
- Stripe integrationLovable docs
- SecretsBolt support
- Env variables and modesVite docs
- Environment variablesNext.js docs
Frequently asked questions
- The key is hidden in an environment variable. Isn't that enough?
- Only if the variable stays on the server. Variables starting with
VITE_orNEXT_PUBLIC_are written into the JavaScript the browser downloads, so a key stored in one is as public as a key written into the page. Secret keys belong in your server functions' secrets. - Is my Stripe publishable key a problem?
- No. Stripe says publishable keys (
pk_) are safe to include in front-end code and apps you distribute: they cannot create charges or read account data. Secret (sk_) and restricted (rk_) keys are the ones that must stay on the server. - My app only has a few users. Does this matter yet?
- Yes. The risk does not depend on how many users you have, but on whether someone opens the page and copies the key. Once they have it, they can use it from anywhere, not just through your app.
- I moved the call to an Edge Function. Can anyone still run up my OpenAI bill?
- Anyone who can sign up and call the function can use it within whatever limits you set, which is why the function checks the user, caps the input size and counts requests per user. Set a hard monthly spend limit on the OpenAI project as a final safety net.
- Do I need a new key if I fix the code?
- Yes, if the old key was ever on a live site or in a public repository. Fixing the code stops new copies, but not the ones already made. Create a new key, store it as a secret, switch over, then revoke the old one.
Related guides
Fixed-price audit
Want someone to check the whole app, not just this?
A review of data security, production readiness and App Store readiness for apps built with AI tools. 900 USD, a ranked list of fixes within 5 business days.