API key exposed in your Lovable, Bolt or Cursor app: how to hide it
AI builders often put the API call right in the React code, so the key ships to every visitor's browser. Anyone can open DevTools, copy your OpenAI or Stripe secret key and run up your bill. Variables starting with VITE_ or NEXT_PUBLIC_ are public by design. Here's how to check and fix it.
1. Check if a key is exposed
Open your live site, right-click → Inspect → Sources (or Network), and search (Ctrl/Cmd+Shift+F) for sk-, sk_live, Bearer and api_key. Also check your repo for VITE_OPENAI or NEXT_PUBLIC_…SECRET. Supabase's anon/publishable key is meant to be public; the service_role or secret key is not.
2. Rotate the key first
If a secret key was ever in the browser, assume it's been copied. Create a new key in the provider's dashboard, then revoke the old one. Set a spending limit while you're there (OpenAI: Settings → Limits).
3. Move the call to the server
The browser should call your endpoint; only the server holds the key. With Supabase, an Edge Function works well:
// supabase/functions/ask/index.ts
Deno.serve(async (req) => {
const { prompt } = await req.json()
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',
messages: [{ role: 'user', content: prompt }] }),
})
return new Response(await r.text(), { headers: { 'Content-Type': 'application/json' } })
})
Store the key with supabase secrets set OPENAI_API_KEY=…. On Vercel or Next.js, use an API route and a variable without the NEXT_PUBLIC_ prefix. Remember CORS headers on the function (see our CORS guide).
4. Stop strangers using your endpoint
A public endpoint that calls OpenAI is just a slower leak. Require a signed-in user (check the JWT in the function, or keep Verify JWT on), and add a simple per-user limit.
5. Clean the repo history
Removing the key from the code doesn't remove it from git history. Rotating (step 2) is what actually protects you. If the repo is public, make it private or treat every key ever committed as burned.
Quick checklist
- No
sk-,sk_liveorservice_rolein the browser bundle - Exposed keys rotated and old ones revoked
- Secret calls made from an Edge Function or server route
- Endpoint requires a signed-in user and has a limit
- Spending limits set with the provider
Still stuck?
Mendlark fixes this kind of problem for a fixed €49 (launch price, normally €79). We agree the problem first, test the fix and send it as a pull request, so nothing changes in your app until you merge it. If we can't fix it, you don't pay. Get the €49 fix, or start with a free scan.
Not sure what else is wrong? Paste your app link into the free instant check and get a plain-English list of problems in seconds.