api keys
API keys in frontend code: why it’s dangerous and how to fix it in Bolt, v0, and Lovable
Learn which keys can live in the browser, why secret keys in client bundles get stolen, and exact fix steps for Bolt, v0, Lovable, and Next.js.
Paste your production URL into the free Vibe Code Health grader for a Semrush-style score on secrets, headers, TLS, and common leaks—then come back to this guide for the fixes.
You asked your AI builder for “Stripe checkout” or “call GPT on this button,” and it worked. Then someone on Twitter asked:
“Is that API key in your frontend?”
If the answer is yes—and it is a secret key—you have a billable incident waiting to happen. This post explains why frontend API keys are dangerous, which keys are supposed to be public, and exactly how to fix the pattern in Bolt, v0, Lovable, and Cursor/Next.js.
It is intentionally about client-side secret leakage, not Supabase anon-vs-service_role deep dives (see Supabase keys) and not header hardening (see Security headers).
Grade your live URL anytime with Vibe Code Health—live secrets in public files force an F.
Public vs secret: the only distinction that matters
| Kind | Examples | Browser OK? |
|---|---|---|
| Publishable / public | Stripe pk_live_, Supabase anon, Firebase web config, many analytics write keys | Yes, by design |
| Secret / privileged | Stripe sk_live_, OpenAI sk-…, Anthropic sk-ant-…, AWS AKIA…, GitHub ghp_, Supabase service_role, private PEM | Never |
Publishable keys are still abrusable in limited ways (someone can spam your checkout form), but they cannot empty your bank account alone. Secret keys can charge cards, spawn cloud VMs, read private repos, or bypass database row locks.
Primary sources:
Why “but it’s minified” does not help
Anything shipped to the browser is public:
- Users open DevTools → Sources / Network.
- Scrapers download your JS bundles.
- Source maps (
.js.map) can reveal original file names and strings. - GitHub search and launch boards advertise new hostnames for automated scanning.
Minification renames variables; it does not encrypt strings. If sk_live_… appears in a .js file, assume it is already copied.
How Bolt, v0, and Lovable accidentally put secrets in the client
AI builders optimize for demos. Typical failure modes:
- One env file, all “public.” The model puts
OPENAI_API_KEYnext toVITE_SUPABASE_URLand both get inlined. - “Just fetch from the button.” A client component calls
https://api.openai.comwith a Bearer token fromimport.meta.env. - Copy-paste from docs into a React file. Tutorial code meant for a server ends up in
App.tsx. - Wrong Next.js prefix. Secrets stored as
NEXT_PUBLIC_OPENAI_KEYare embedded in the browser bundle by design.
Vite / Bolt-style anti-pattern
// ❌ Dangerous — bundled into the client
const apiKey = import.meta.env.VITE_OPENAI_API_KEY;
await fetch("https://api.openai.com/v1/chat/completions", {
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ model: "gpt-4o-mini", messages }),
});
Anything prefixed for client exposure (VITE_, NEXT_PUBLIC_, many “public env” toggles in builders) is visible to visitors.
Safer pattern: browser → your backend → vendor
// ✅ Browser calls YOUR backend only
await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages }),
});
// ✅ Server route (Next.js App Router example)
import OpenAI from "openai";
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
export async function POST(req: Request) {
const { messages } = await req.json();
// Add auth + rate limits before calling vendors
const completion = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages,
});
return Response.json(completion);
}
Keep OPENAI_API_KEY in server-only env (Vercel/Host secrets). Never NEXT_PUBLIC_.
Stripe’s equivalent: use Checkout Sessions or PaymentIntents created on the server; the browser receives a client secret / publishable key, not sk_live_.
Platform-by-platform fix checklist
Lovable
- Open project secrets / env settings.
- Mark OpenAI, Stripe secret, Supabase service role as secret / server (not public).
- Prompt: “Move all secret API calls to a backend function. Client components must not read secret env vars.”
- Redeploy. Search the live JS for
sk_/service_role. - Rotate any key that was ever public.
Bolt
- Audit env vars exposed to the web container vs server.
- Replace client
fetchto OpenAI/Stripe secret APIs with a Bolt backend/server function. - Ensure secret values are not prefixed for client bundling.
- Redeploy + rotate leaked keys.
v0 / Vercel
- In Vercel project settings → Environment Variables, secrets must not start with
NEXT_PUBLIC_. - Put vendor calls in Route Handlers (
app/api/.../route.ts) or Server Actions. - Redeploy production (preview env can differ!).
- Rotate keys that appeared in older client bundles—old deployments may still be reachable.
Cursor + local Next.js
- Use
.env.localfor secrets; add.env*to.gitignoreif not already. - Grep the repo:
rg "sk_live|OPENAI_API_KEY|service_role" --glob '!node_modules'. - Prefer server components / route handlers for privileged calls.
- On Vercel, mirror the same server-only names.
What to do if a secret already leaked
Treat it as compromised—even if traffic is low.
- Rotate immediately in the vendor dashboard (Stripe, OpenAI, Anthropic, AWS, GitHub, Supabase).
- Revoke the old key; do not only “add a new one.”
- Check vendor logs for abuse (OpenAI usage, Stripe events, AWS CloudTrail).
- Remove the key from git history if it was committed (GitHub: removing sensitive data).
- Redeploy clean builds; re-scan with Vibe Code Health.
- Add rate limiting and auth on your new backend proxy so strangers cannot burn credits through your
/api/chat.
Add a thin layer of abuse protection on the proxy
Moving the key server-side is necessary but not sufficient. Anyone who can hit /api/chat can still spend your money. Minimum bar:
- Require a logged-in session (or signed cookie)
- Rate limit by IP and user id
- Cap max tokens / dollars per day
- Validate and truncate input size
Example sketch (pseudo-production):
export async function POST(req: Request) {
const session = await getSession(req);
if (!session) return new Response("Unauthorized", { status: 401 });
if (await tooManyRequests(session.userId)) {
return new Response("Slow down", { status: 429 });
}
const body = await req.json();
if (!Array.isArray(body.messages) || body.messages.length > 20) {
return new Response("Bad request", { status: 400 });
}
// …call OpenAI with server key…
}
Quick self-test (five minutes)
- Open your production site.
- View source / Network → JS → search
sk_live,sk-,service_role,AKIA. - Visit
https://your-host/.env(should 404). - Paste the URL into Vibe Code Health.
- If anything critical appears: rotate, fix, re-scan before you tweet the link.
Prompt you can paste into Bolt, v0, or Lovable
Use this after you rotate any leaked key:
Refactor so no secret API keys exist in client/browser code.
Rules:
1. OpenAI, Anthropic, Stripe secret keys (sk_), AWS keys, GitHub tokens, and Supabase service_role must only live in server-only environment variables.
2. Client components may call our own /api/* routes only — never vendor secret endpoints with Bearer secrets.
3. Do not use NEXT_PUBLIC_, VITE_, or “public env” for secrets.
4. Add basic auth or session checks and rate limiting on the proxy routes.
5. Show me which files changed and how to set the server env vars on this host.
Then redeploy and search the live JavaScript again. Automation helps: paste the URL into Vibe Code Health and confirm the secrets category is clean.
FAQ
Is a Stripe publishable key (pk_) a problem?
No—expected in the browser. Never confuse it with sk_.
Is a Supabase anon key a problem?
No by itself. Missing RLS is the problem. See RLS for beginners.
Can I encrypt the key in frontend code?
No. Anything the browser can decrypt, an attacker can decrypt.
Will an A grade from Vibe Code Health mean I’m unhackable?
No. It means we did not find serious publicly visible issues on a passive scan. It is not a pentest.
What if the AI builder keeps putting the key back?
Be explicit in the prompt that secrets are server-only, delete public env entries in the UI, and rotate the key so the old value is useless even if a stale bundle remains online for a while.
Next reads
- How to check if your vibe-coded app is safe before launch
- Supabase keys in vibe-coded apps
- Lovable app security checklist
Secret keys in frontend code are not a style issue—they are a shared credit card on the sidewalk. Move them behind your own API, rotate anything that leaked, and grade the public URL before you launch.