// guide · API keys · published Nov 17, 2026
Is your OpenAI or Stripe secret key in your frontend? Find it in 60 seconds and fix it
Short answer
Any variable prefixed VITE_, NEXT_PUBLIC_, REACT_APP_ or EXPO_PUBLIC_ is baked into the JavaScript every visitor downloads, and so is any key pasted into a component. Search your live site's JS for sk-, sk_live_, sb_secret_ and a service_role JWT. If you find one, move the call to a server route or Supabase Edge Function that checks the user and rate-limits, then rotate the key: moving it doesn't un-leak it. The Supabase anon/publishable key and Stripe pk_ key are meant to be public.
Why AI-built apps leak keys this way
Lovable, Bolt and most Vite apps have no server of their own, so the first time an agent wires up OpenAI, Stripe or Resend, the call goes in a React component. The key isn't visible to browser code until it gets a public prefix, so the agent adds one, or sets the OpenAI SDK's dangerouslyAllowBrowser: true (a flag the SDK added precisely to warn you; openai-node docs). The feature works, and the key is now in a public file. Vite's docs say VITE_ variables should not contain sensitive information (Vite env docs); Next.js inlines NEXT_PUBLIC_ values into the browser bundle at build time (Next.js env docs); Expo says the same for EXPO_PUBLIC_ (Expo docs).
// .env (Vite / Lovable / Bolt)
VITE_OPENAI_API_KEY=sk-proj-... // VITE_ = shipped to every visitor
// src/lib/ai.ts (runs in the browser)
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: import.meta.env.VITE_OPENAI_API_KEY,
dangerouslyAllowBrowser: true, // the SDK's own warning, switched off
});
// Next.js: same problem with NEXT_PUBLIC_STRIPE_SECRET_KEY, NEXT_PUBLIC_SUPABASE_SERVICE_ROLE_KEY ...Leaked AI keys get found and used to run up bills; leaked Stripe secret keys can issue refunds, read customers and create charges; a leaked Supabase service_role key reads and writes every table regardless of RLS. Minifying or splitting the bundle doesn't hide a string.
Which keys are fine to be public
| Fine in the browser | Never in the browser or git |
|---|---|
Supabase anon / sb_publishable_ key (with RLS on) | Supabase service_role JWT / sb_secret_ key |
Stripe pk_live_ / pk_test_ | Stripe sk_live_ and restricted rk_live_ keys, whsec_ secrets |
| Firebase web config | OpenAI sk-, Anthropic sk-ant-, xAI xai-, Groq gsk_, Gemini keys |
| Google Maps browser key restricted by HTTP referrer | Resend / SendGrid / Twilio tokens, database URLs with passwords |
Supabase's rule of thumb: use the publishable key for anything you ship, and the secret key only for code you control (Supabase API keys docs). The newer sb_secret_ keys return 401 when Supabase sees a browser User-Agent, but that doesn't stop anyone using a copied key from a script. Stripe's equivalent is publishable vs secret/restricted keys (Stripe API keys docs).
Check your live site in 60 seconds
Fastest: open your deployed app, open DevTools, click around the pages that use AI or payments, then search all loaded sources with Ctrl/Cmd + Shift + F for sk-, sk_live_, rk_live_, sb_secret_, xai- and dangerouslyAllowBrowser. Or run this against your own site:
# Your OWN site only. Downloads the JS your homepage loads and looks for secret-key prefixes.
SITE=https://your-app.com
curl -s "$SITE" | grep -oE '(src|href)="[^"]+\.js[^"]*"' | cut -d'"' -f2 | sort -u |
while read -r p; do
case "$p" in
http*) u="$p" ;;
//*) u="https:$p" ;;
/*) u="$SITE$p" ;;
*) u="$SITE/$p" ;;
esac
curl -s "$u"
done > /tmp/bundle.js
# Prints only the first 12 characters of each match, so you don't paste whole keys into chat.
grep -oE 'sk-(proj-|ant-)?[A-Za-z0-9_-]{20,}|sk_live_[A-Za-z0-9]{20,}|rk_live_[A-Za-z0-9]{20,}|sb_secret_[A-Za-z0-9_-]{10,}|xai-[A-Za-z0-9]{20,}|gsk_[A-Za-z0-9]{20,}|service_role' /tmp/bundle.js |
cut -c1-12 | sort | uniq -c
# Supabase legacy keys are JWTs: check each one's role (anon = fine, service_role = leak)
node -e 'const s=require("fs").readFileSync("/tmp/bundle.js","utf8");for(const t of s.match(/eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g)||[])console.log(JSON.parse(Buffer.from(t.split(".")[1],"base64url")).role)'The script only fetches the scripts your homepage references, so code-split chunks for other routes can be missed; the DevTools search after clicking around covers those. Any hit other than anon or a pk_ key is a real leak.
Check the repo and git history
A key can be gone from today's code and still sit in an old commit of a public repo:
# Public-prefixed variables that look like secrets
grep -rnE '(VITE|NEXT_PUBLIC|REACT_APP|EXPO_PUBLIC)_[A-Z0-9_]*(SECRET|SERVICE_ROLE|PRIVATE|OPENAI|ANTHROPIC|XAI|GEMINI|GROQ|STRIPE_SECRET|RESEND|TWILIO|DATABASE_URL)' \
--include='*.ts' --include='*.tsx' --include='*.js' --include='*.jsx' --include='.env*' . | grep -v node_modules
# AI SDKs running in the browser
grep -rn 'dangerouslyAllowBrowser' --include='*.ts' --include='*.tsx' --include='*.js' . | grep -v node_modules
# Keys committed at any point, even if a later commit deleted them
git log -p --all -S 'sk-' | grep -E '^\+.*sk-' | cut -c1-40
git log -p --all -S 'sk_live_' | grep -E '^\+.*sk_live_' | cut -c1-40GitHub push protection blocks many known key formats when you push to a public repo (GitHub docs), but it doesn't catch everything, and it can't help with keys that are only in the built bundle.
The fix: call the provider from the server
Drop the public prefix so the bundler stops shipping the value, and put the call behind an endpoint you control that checks who is calling. In Next.js, a route handler, with import "server-only" so a client component can never import it by accident:
// .env.local (no NEXT_PUBLIC_ prefix = server-only)
OPENAI_API_KEY=sk-proj-...
// app/api/chat/route.ts (runs on the server)
import "server-only";
import OpenAI from "openai";
import { createClient } from "@/lib/supabase/server";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function POST(req: Request) {
const supabase = await createClient();
const { data: { user } } = await supabase.auth.getUser();
if (!user) return new Response("Unauthorized", { status: 401 });
// + a per-user rate limit / credit check here before you spend money
const { message } = await req.json();
const r = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: String(message).slice(0, 4000) }],
});
return Response.json({ reply: r.choices[0].message.content });
}
// Browser code calls YOUR endpoint, never the provider:
// await fetch("/api/chat", { method: "POST", body: JSON.stringify({ message }) })No server (Lovable, Bolt, plain Vite)? Use a Supabase Edge Function and store the key as a function secret (Supabase secrets docs):
# Supabase Edge Function (Lovable / Bolt / Vite apps without a server)
supabase secrets set OPENAI_API_KEY=sk-proj-...
// supabase/functions/chat/index.ts
// Deployed with JWT verification ON (the default), so only signed-in users get through.
Deno.serve(async (req) => {
const { message } = 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: String(message).slice(0, 4000) }] }),
});
return new Response(await r.text(), { headers: { "Content-Type": "application/json" } });
});
// Browser: const { data } = await supabase.functions.invoke("chat", { body: { message } });Either way, an endpoint that anyone can call with no login or limit is just a slower leak: it still spends your money. Require a signed-in user and add a per-user rate limit or credit check before the provider call.
Rotate what leaked, in this order
- Ship the server-side version with a new key first, so the app keeps working.
- Revoke the old key: OpenAI/Anthropic/xAI dashboards (API keys), Stripe Dashboard → Developers → API keys (roll the key), Supabase → Settings → API Keys (create a new secret key, delete the leaked one; the legacy service_role JWT can only be replaced by moving to the new keys or rotating the JWT secret).
- Check usage and logs for the period the key was public: AI usage spikes, unexpected Stripe refunds or customers, rows changed with the service role.
- Set a monthly budget or spend limit on each AI provider so the next mistake has a ceiling.
Tell your AI coding tool
Paste this into Lovable, Bolt, Cursor or Claude Code:
Audit this project for secret API keys that reach the browser.
1. List every environment variable with a VITE_, NEXT_PUBLIC_, REACT_APP_ or EXPO_PUBLIC_ prefix and say whether its value is meant to be public (Supabase anon/publishable key, Stripe pk_ key, Firebase web config) or secret (OpenAI/Anthropic/xAI/Gemini keys, Stripe sk_/rk_ keys, Supabase service_role or sb_secret_ keys, email/SMS tokens, database URLs).
2. Find any hardcoded keys in source files and any use of dangerouslyAllowBrowser.
3. For each secret: rename the variable without the public prefix, move the code that uses it into a server route (Next.js route handler with import "server-only") or a Supabase Edge Function that requires a signed-in user and applies a per-user rate limit, and change the browser code to call that endpoint.
4. Never "fix" a missing-key error by adding a public prefix or by using the service_role key in the browser.
5. Give me a list of every key that was exposed so I can rotate it, and add .env* (except .env.example) to .gitignore.Check your repo automatically
RescueMyRepo's free scan flags secret-looking public env vars, hardcoded Supabase service_role and sb_secret_ keys (it decodes the JWT, so the anon key isn't a false alarm), service-role variables read from browser code, AI SDKs with dangerouslyAllowBrowser, AI routes with no login check or rate limit, committed .env files, and keys anywhere in git history. Each finding comes with a fix prompt. It reads the repo, not the deployed bundle, so run the 60-second check above on the live site too.
FAQ
Is it safe to put an API key in a VITE_ or NEXT_PUBLIC_ variable?
Only if the key is meant to be public. Vite exposes VITE_ variables to client code and its docs say they should not contain sensitive information; Next.js inlines NEXT_PUBLIC_ values into the JavaScript sent to the browser at build time. The same goes for REACT_APP_ (Create React App) and EXPO_PUBLIC_ (Expo). Putting a secret there is the same as publishing it.
My Supabase anon key is in the frontend. Is that a leak?
No. The anon (legacy) or publishable key is designed to ship in the browser; Supabase's docs describe it as safe to expose, and it only reaches what your Row Level Security policies allow. The service_role key and the newer sb_secret_ keys bypass RLS and must never be in the browser or in git. A leaked anon key only becomes a problem when RLS is off or too loose.
Which other keys are fine to be public?
Keys designed for the browser: the Stripe publishable key (pk_live_ / pk_test_), Firebase web config, Supabase anon/publishable keys, and Google Maps browser keys restricted by HTTP referrer. Not fine: OpenAI, Anthropic, xAI, Gemini or Groq keys, Stripe secret (sk_) and restricted (rk_) keys, Resend/SendGrid/Twilio tokens, database URLs with passwords, and Supabase service_role / sb_secret_ keys.
I moved the key to the server. Am I done?
No. Rotate it. Once a key has shipped in a public bundle or a public commit, assume someone copied it; moving it doesn't take it back, and it stays in old deploys and git history. Create a new key, deploy with it, then revoke the old one. Add a spend limit or budget on AI providers so a future leak has a ceiling.
Will my AI coding tool make this mistake again?
Often, yes. When a call fails because the key is missing in the browser, the quickest fix an agent finds is to prefix the variable with VITE_ or NEXT_PUBLIC_, or to set dangerouslyAllowBrowser: true in the OpenAI SDK. Put a rule in your AI tool's instructions: secret keys are server-only, and browser code calls your own endpoint.
Does RescueMyRepo detect this?
Yes, from the repo. The free scan flags secret-looking VITE_/NEXT_PUBLIC_/REACT_APP_/EXPO_PUBLIC_ variables, hardcoded Supabase service_role keys (decoded, not guessed) and sb_secret_ keys, service-role env vars read from browser code, AI SDKs used with dangerouslyAllowBrowser, committed .env files with secret values, and leaked keys anywhere in git history (gitleaks). It doesn't download your live bundle, so also run the 60-second check below on the deployed site.
Related
- Did Claude Code commit your secrets? Check .claude/settings.local.json
- Can anyone fake a Stripe payment in your AI-built app?
- Is your Lovable app one of the 7,403? Check your Supabase data isn't readable without a login