Secrets in the Browser: How AI-Built Apps Leak API Keys
AI-built apps leak API keys through client code, NEXT_PUBLIC_ and VITE_ variables, source maps and git history. Check yours in 15 minutes, then fix it.
AI-built apps leak API keys in six ways: keys hard-coded in client components, secrets stored in NEXT_PUBLIC_, VITE_ or EXPO_PUBLIC_ variables that get compiled into the JavaScript bundle, the Supabase service_role key used in browser code, published source maps, git history, and keys pasted into AI chats. It’s common: in 2025, security vendor Escape found 400+ exposed secrets across 5,600 public vibe-coded apps, and Vercel counted more than 17,000 v0 deployments blocked in 30 days for exposed secrets alone. The fix has two halves and you need both: move the call to a server, and rotate the key, because deleting it from the code doesn’t un-leak it.
Key takeaways
- Anything the browser downloads is public. Minified code is still readable, and a
NEXT_PUBLIC_,VITE_orEXPO_PUBLIC_prefix is an instruction to publish the value. - Some keys are designed to be public. Supabase publishable keys, Stripe
pk_keys and Firebase web config belong in the bundle. Your access rules protect you there, not secrecy. - Leaked keys are found by machines, fast. In one vendor test, AWS keys posted to GitHub were used within a minute. Google’s threat team has seen stolen LLM access run up more than $100,000 in charges in a single day.
- Rotate; don’t just delete. GitGuardian reports that more than 64% of the secrets it confirmed valid in 2022 still worked in January 2026.
- You can check your own app in 15 minutes with browser DevTools and a free scanner.
Exposed secrets are one of the failures we cover in How Much Does It Cost to Fix a Vibe-Coded App in 2026?, and section 3 of our production-readiness checklist has six checks for them. This post goes a level deeper.
Six ways a key ends up public
Lovable, Bolt, Replit, Cursor and v0 all get you to a working screen quickly. When a feature needs a paid API, the agent has to put the key somewhere, and the browser code is closest. Vercel says LLMs place database credentials and API keys in public variables and hard-code them in source files. (We compare where each builder keeps secrets in Lovable vs Bolt vs Replit vs Cursor.)
1. Hard-coded in a client component
You paste a key into the chat, and it comes back as a string in a React component or a lib/ file that ships to every visitor.
One tell is worth searching your code for. OpenAI’s JavaScript SDK refuses to run in a browser by default so credentials don’t get exposed. The opt-out is an option named dangerouslyAllowBrowser. If that string is in your codebase, a safety check was switched off to make an error go away.
2. Environment variables with a public prefix
Moving the key into a .env file looks like the fix. It isn’t if the variable’s name starts with a public prefix.
| Framework | Prefix | What the framework’s docs say |
|---|---|---|
| Next.js | NEXT_PUBLIC_ |
The value is inlined into the JavaScript sent to the browser at build time |
| Vite | VITE_ |
Values are bundled into client code and shouldn’t contain sensitive information such as API keys |
| Expo (React Native) | EXPO_PUBLIC_ |
Values are visible in plain text in the compiled app |
The prefixes exist for values that are meant to be public, like an analytics ID. In Next.js, a variable without the prefix is only available on the server. A Vite single-page app has no server of its own, so a variable without the prefix is simply missing in the browser. The feature breaks, the prefix gets added, the feature works, and the key is in the bundle.
3. The Supabase service_role or secret key in browser code
Supabase has two kinds of key. The publishable key (sb_publishable_..., or the legacy anon JWT) is built to be exposed. The secret key (sb_secret_..., or the legacy service_role JWT) bypasses every Row Level Security policy. Agents reach for it for the same reason they write using (true) policies, which we cover in Supabase Row Level Security: 10 Mistakes AI-Built Apps Make: a query returns nothing, and the stronger key makes the rows appear.
Escape’s scan found Supabase service keys that were trivially retrievable from front-end bundles. New-format secret keys get a 401 when a browser sends them, which breaks the app but doesn’t stop anyone using the leaked key from curl. Supabase is deprecating the legacy keys by the end of 2026.
4. Source maps
A source map lets the browser reconstruct your original code from the minified bundle. Next.js disables them in production builds by default, and Vite’s build.sourcemap defaults to false. If someone turned them on for debugging, anyone can read your original files in DevTools.
A map doesn’t add a key the bundle didn’t already contain. It makes the key easy to find and shows an attacker how the rest of your app fits together.
5. Git history and public repos
Deleting a key in a new commit leaves it in every earlier one. GitGuardian counted 28.65 million new hardcoded secrets in public GitHub commits in 2025, up 34% on the year before, with AI-service keys up 81% (vendor numbers). GitHub’s own guidance is to revoke or rotate the secret first. Rewriting history comes second, because the commit can survive in forks and clones anyway.
A private repo isn’t a vault either: GitGuardian finds internal repositories about six times more likely than public ones to contain hardcoded secrets, and every contractor and connected tool gets the full history.
6. Keys pasted into AI chats and tool configs
Founders paste keys into the builder’s chat to wire up an integration. Lovable detects keys pasted into chat and points you to its Secrets store, but the chat log is still a copy of the key you don’t control. Between February 3 and April 20, 2026, chat history and source code of public Lovable projects could be opened by any Lovable user with the project link.
With Cursor-style tools the same thing happens in configuration files. GitGuardian found 24,008 unique secrets in MCP configuration files on public GitHub, 2,117 of them valid. It also measured commits assisted by Claude Code leaking secrets at 3.2%, against a 1.5% baseline, and attributed that to how people work, not to the tool.
What happens after a key leaks
Nobody has to target you. Stripe says bad actors continuously scan public repositories for Stripe keys. Clutch Security planted AWS keys on public platforms and saw the GitHub ones used in about a minute (vendor research).
What it costs you depends on the key:
- LLM keys become someone else’s compute. Sysdig named this “LLMjacking” in 2024 and estimated a worst case of over $46,000 a day. In November 2026, Google’s threat intelligence team reported incidents with more than $100,000 of fraudulent charges in one day, and $1 million in total at some organizations. One actor harvested LLM keys from public GitHub repositories.
- Small teams get hit too. The Register reported on a three-developer startup billed $82,314 in about 48 hours after its Gemini key was compromised. Its usual bill was $180 a month. How the key got out wasn’t reported.
- A
service_rolekey or database URL is a data breach, not a bill. A Supabase secret key gives full access to the project’s data.
Which keys are meant to be public
Not every key in your bundle is a problem. Some are identifiers the provider expects you to publish.
| Key and how to recognize it | Safe in the browser? | If you find it there |
|---|---|---|
Supabase publishable key (sb_publishable_...) or legacy anon JWT (eyJ...) |
Yes. It reaches only what Row Level Security allows | Leave it, and test your RLS policies |
Supabase secret key (sb_secret_...) or legacy service_role JWT (eyJ...) |
No. It bypasses RLS | Assume the database was readable. Rotate it and move the code into an Edge Function |
Stripe publishable key (pk_live_, pk_test_) |
Yes | Nothing |
Stripe secret key (sk_live_, sk_test_) or restricted key (rk_live_, rk_test_) |
No | Rotate with immediate expiry, read the key’s request logs, switch to a restricted key |
Stripe webhook signing secret (whsec_) |
No. It’s how your server knows an event came from Stripe | Roll the secret and redeploy the handler |
Firebase web config (apiKey: "AIza...") |
Yes. It identifies the project; Security Rules and App Check protect the data | Check the key’s API restrictions. Gemini must not be on the list |
Google Maps JavaScript key (AIza...) |
Yes, once restricted to your websites and the Maps APIs you use | Add both restrictions |
OpenAI key (sk-proj-..., older sk-...), Anthropic key (sk-ant-...) or Gemini API key |
No (OpenAI, Anthropic, Google) | Rotate, move the call server-side, set a spend limit |
Database URL (postgresql://user:password@host/db) |
No. It contains the database password | Change the password. Connect only from server code |
| JWT secret | No. Its holder can impersonate your users | Rotate it. On Supabase, move to asymmetric signing keys |
The OpenAI, Anthropic and AIza prefixes come from gitleaks’ default rules.
One trap sits in the Google rows. Truffle Security showed that enabling the Gemini API on a Google Cloud project could let existing public AIza keys authenticate to Gemini, and found 2,863 live examples on the public web. Firebase’s docs say to never allow the Gemini Developer API on a publicly accessible key.
Check your own app in 15 minutes
1. Search the JavaScript your site ships (5 minutes)
Open your live site in Chrome and click through the main screens so every chunk loads. In DevTools, open the Search panel (Cmd+Option+F on a Mac, Ctrl+Shift+F on Windows or Linux), which searches every resource the page has loaded. Turn on the regular-expression toggle and search for:
sk_live_|rk_live_|sk_test_|whsec_|sk-proj-|sk-ant-|sb_secret_|postgres(ql)?://
Any hit is a secret in public. Then search for AIza and check each hit against the table above. Finally, search for eyJ. Those are JWTs, and a Supabase app on legacy keys will show one. Supabase tokens carry a role claim, so paste this into the Console to see which key you’ve shipped:
const part = "PASTE_THE_eyJ_STRING_HERE".split(".")[1];
JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/"))).role;
// "anon" is expected. "service_role" means stop and rotate today.
2. Look for source maps (2 minutes)
In the Sources panel, if you can browse your original src/ folder and read .tsx files, your maps are public. You can also check the last line of a .js bundle for a sourceMappingURL comment, which is how the browser finds the map.
3. Scan the repo and its history (5 minutes)
# Every commit on every branch, with secrets masked in the output
gitleaks git -v --redact --log-opts="--all" .
# Second opinion: TruffleHog tests each hit against the provider
trufflehog git file://. --results=verified,unknown
# The build output you actually ship (dist for Vite)
npm run build && gitleaks dir -v --redact dist
gitleaks matches known key patterns. TruffleHog also tests each credential against the provider’s API, so verified means the key works right now. No scanner knows every format: gitleaks’ default rules have no Supabase-specific pattern, for example. That’s why the bundle search comes first.
4. Turn on GitHub’s own scanning (3 minutes)
On public repositories, GitHub’s secret scanning runs automatically and free across your entire history. Organization-owned private repos need GitHub Secret Protection on a Team or Enterprise plan. Push protection blocks a push containing a recognized secret before it reaches the repo, and is on by default for your own pushes to public repositories.
Some providers act on a key found in a public repo: Anthropic deactivates it, and Supabase revokes new-format secret keys. Treat that as a backstop. GitHub reads repositories, not the JavaScript your site serves.
Fix it properly
Move the call to a server
The wrong pattern: the key is in a public variable, and the SDK’s warning is switched off.
// src/lib/ai.ts: runs in every visitor's browser
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: import.meta.env.VITE_OPENAI_API_KEY, // compiled into the bundle
dangerouslyAllowBrowser: true, // the SDK's safety check, switched off
});
The right pattern keeps the key on a server and lets the browser ask for the result. On Supabase, that’s an Edge Function. Secrets are set with supabase secrets set and read with Deno.env.get, and the withSupabase wrapper in user mode accepts only callers with a valid user JWT:
// supabase/functions/summarize/index.ts: runs on the server
import OpenAI from "npm:openai";
import { withSupabase } from "npm:@supabase/server@1";
const openai = new OpenAI({ apiKey: Deno.env.get("OPENAI_API_KEY") });
export default {
fetch: withSupabase({ auth: "user" }, async (req, ctx) => {
const { text } = await req.json();
if (typeof text !== "string" || text.length > 8000) {
return Response.json({ error: "Invalid input" }, { status: 400 });
}
// Enforce a per-user limit here, keyed on ctx.userClaims?.id
const res = await openai.responses.create({
model: "gpt-5.5",
input: `Summarize this:\n\n${text}`,
});
return Response.json({ summary: res.output_text });
}),
};
// In the browser: send the text and the user's session, never a key
const { data, error } = await supabase.functions.invoke("summarize", {
body: { text },
});
On Next.js the same move is a Route Handler that reads process.env.OPENAI_API_KEY, with no NEXT_PUBLIC_ prefix. Lovable’s docs describe the same shape: key in Secrets, call from server-side code.
A proxy with no checks is the same open tap. Require a signed-in user, cap the input size, and limit calls per user.
Rotate the key; deleting it isn’t enough
Once a key has been in a bundle, a repo or a chat, treat it as used. Stripe’s guidance is to rotate immediately, even if you aren’t sure anyone saw it. In the Stripe Dashboard, set a leaked key to expire “Now”, not after the grace period.
Restrict the keys you keep
- Google Maps: restrict the key to your websites and to the Maps APIs you use. Google says you’re financially responsible for abuse of unrestricted keys.
- Stripe: use restricted keys with an access policy, so a key has only the permissions it needs and works only from your servers.
- LLM providers: Google’s threat team recommends separate keys per environment and per model tier, so a leaked key for a cheap model can’t call an expensive one.
Cap the spend
A cap turns a runaway bill into a failed request. OpenAI projects support a hard monthly spend limit, after which requests return a 429. Alerts alone don’t stop anything. Anthropic describes spend limits as a safeguard against leaked keys.
Use different keys per environment
Stripe gives every sandbox its own sk_test_ keys, OpenAI recommends separate projects for staging and production, and Supabase suggests a separate secret key for each backend component. One leak then means one rotation.
Rotation checklist
For every key that failed the check:
- List where the key is used: host environment variables, Edge Function secrets, CI, teammates’
.envfiles. Names, not values. - Close the leak first. Move the call server-side and deploy. Supabase’s rotation guide says to fix the root cause before rotating, or the new key leaks the same way. If the key is being abused right now, revoke it first and accept the downtime.
- Create the replacement with the narrowest scope the provider offers.
- Store it server-side only. No public prefix, and never back into a chat.
- Deploy, then confirm traffic is on the new key. Stripe shows request logs per key.
- Revoke the old key. For a legacy Supabase
service_rolekey, that means disabling the legacy keys and revoking the legacy JWT secret. - Read the provider’s logs and bill for the exposure window.
- If the key could read user data, treat it as a possible breach. Under GDPR you have 72 hours to notify the regulator once you know personal data was exposed.
- Add a guard and write it down. A gitleaks pre-commit hook and GitHub push protection stop the next one. Record the rotation date and an owner in your secrets list.
Have senior engineers check the rest
The 15-minute check finds keys with a recognizable prefix in the places you thought to look. In our AI-App Rescue Audit, senior engineers go through your code the way an attacker would. Day one is automated scans, then a manual review of auth, data access and secrets. It’s $1,490, fixed, and delivered in 72 hours. Every finding is ranked by severity and comes with evidence, impact and the exact fix. You also get a 45-minute walkthrough with the engineers who did the audit, and a refactor-or-rebuild verdict with a fixed quote for the work.
We work from read-only access to your repository, a staging URL, and the names of your environment variables, never the values. If we find fewer than five material issues, you get a full refund. Book the Stabilization Sprint (from $7,500 for two weeks) within 30 days and the full audit fee is credited to it.
To talk it through first, book a call and tell us what the search turned up.