API Key Leaked? What to Do and How to Find Exposed Keys in Your App
Find exposed API keys in AI-built apps: frontend bundles, public env variables and Git history, plus a clear plan for the first hour after a key leaks.
You built an app with an AI coding assistant, connected OpenAI, Stripe, an email service and a database, and now you are wondering whether one of those keys is sitting somewhere it should not be. If an API key leaked, what to do in the next hour matters more than anything else. This guide shows you where keys typically hide in AI-generated code, how to check your own app in about 20 minutes, and a calm, step-by-step plan for the moment you find one.
Why AI-generated apps leak keys so often
AI coding tools are very good at making things work quickly. When you ask for "call OpenAI from the chat screen", the shortest path to a working feature is often to call the API straight from the browser with the key in the code. It works on the first try, so nobody questions it.
A few patterns make this more likely in AI-built apps:
- The assistant optimizes for "it runs". A server route, authentication and rate limiting are extra steps. Unless you ask for them, you may not get them.
- Public prefixes look like a fix. When a variable is undefined in the browser, a common suggestion is to rename it with the framework's public prefix. The error goes away, and the secret is now part of the JavaScript bundle that every visitor downloads.
- Keys get pasted into chat and code. During debugging, it is tempting to paste the real key into a file "just for now". That file then gets committed.
- Fast iteration means many commits. A key that existed in the code for ten minutes three weeks ago is still in your Git history.
None of this means AI tools are unsafe to use. It means the review step a senior developer would normally do has to happen somewhere. Our overview of AI coding agents and development platforms covers where these tools shine and where they need a human check.
Where keys hide: bundles, public env variables, Git history, logs
Exposed keys usually end up in one of four places.
1. The frontend bundle
Anything the browser runs, the user can read. Minification does not hide a string; it only makes the code harder to read for humans. If your React, Vue or Svelte code contains a secret, it is public, even if the repository is private.
2. Public environment variables
Modern frameworks split environment variables into "server only" and "exposed to the browser". The exposed ones are recognized by a prefix or a config section:
| Framework | Exposed to the browser | Stays on the server |
|---|---|---|
| Vite (React, Vue, Svelte projects) | Variables starting with VITE_, read via import.meta.env | Variables without the prefix (not available in client code) |
| Next.js | Variables starting with NEXT_PUBLIC_ | All other variables, used in server components, route handlers and API routes |
| Nuxt | Keys under runtimeConfig.public, overridable with NUXT_PUBLIC_... | Keys directly under runtimeConfig, overridable with NUXT_... |
Other frameworks use similar conventions, such as a PUBLIC_ or EXPO_PUBLIC_ prefix. The rule is the same everywhere: a public prefix means "this value will be shipped to every visitor". A secret must never have one.
3. Git history
Deleting a key from the current code does not remove it from earlier commits. Anyone with access to the repository, or to a fork or old clone of it, can find it. If the repository was ever public, even briefly, assume the key was seen. Automated scanners watch public code hosting sites for exactly this.
4. Logs and error tools
Keys also leak through:
console.log(process.env)or debug output left in place- build logs on your hosting platform that print the environment
- error tracking tools that capture request headers
- automation tools where a credential was pasted into a plain text field instead of a credential store, which is a common issue we also cover in our n8n security hardening guide
How to check your own app in 20 minutes
Do this on your own app only. You need the code, access to the deployed site and about 20 minutes.
Step 1: Search the live site (5 minutes). Open your deployed app, open the browser developer tools and use the "search in all files" function of the Sources panel. Search for typical key patterns:
sk-andsk_live_(common prefixes for OpenAI and Stripe secret keys)service_role(Supabase admin key)secret,token,apiKey,Bearer
Then open the Network panel, use the app normally and look at outgoing requests. If a request from the browser goes directly to a paid API with an Authorization header, that key is exposed.
Step 2: Search the build output (5 minutes). Build the app locally and search the output folder, for example dist/, .next/static/ or .output/public/:
grep -rnE "sk-|sk_live_|service_role|BEGIN PRIVATE KEY" dist/
Step 3: Review your environment variables (5 minutes). Open your .env files and your hosting platform's environment settings. For every variable with a public prefix, ask: "Would I be fine with this value on a billboard?" If not, it is in the wrong place. Also confirm that .env is listed in .gitignore and that only a .env.example with placeholder values is committed.
Step 4: Scan the Git history (5 minutes). Use an open-source secret scanner such as Gitleaks or TruffleHog on the full repository history. Both scan past commits, not only the current files. Check their official documentation for the current command, as options change between versions. For a quick manual search, Git can find every commit that added or removed a string:
git log -p --all -S "sk_live_"
If your code is on GitHub, also enable its secret scanning and push protection where your plan allows. Push protection blocks many known key formats before they reach the repository.
Which keys may be public and which never may be
Not every key is a secret. Some are designed to sit in the browser and are protected by other rules. The question is always: what can someone do with this value alone?
| Usually fine in the browser | Never in the browser |
|---|---|
Stripe publishable key (pk_...) | Stripe secret key (sk_...) and restricted keys |
| Supabase anon or publishable key, if Row Level Security is on for every table | Supabase service_role or secret key |
| Firebase web config, if security rules are set | Firebase service account JSON |
| Maps or analytics keys restricted to your domain | OpenAI, Anthropic and other LLM API keys |
| Email provider keys (SendGrid, Postmark, Resend and similar) | |
| Database connection strings, webhook signing secrets, JWT secrets |
The left column comes with a condition. A Supabase anon key is safe only if your database rules are correct; check that every table has Row Level Security enabled with policies that match who should see what. A public maps key without domain restrictions can still run up a bill.
API key leaked? What to do in the first hour
If you find a secret where it should not be, treat it as compromised. Do not spend time trying to prove whether anyone used it. Act first, investigate second.
Minutes 0 to 15: Revoke and rotate
- Create a new key in the provider's dashboard.
- Put the new key in the right place: your hosting platform's server-side environment settings, not a public variable.
- Deploy.
- Revoke the old key. If revoking first would break a business-critical feature, keep the gap as short as possible, but do not leave the old key active "until next week".
For a database or admin key, also change any password or connection string tied to it.
Minutes 15 to 40: Review what happened
- Usage and billing. Check the provider's usage dashboard for unusual spikes, unknown models, new regions or requests at odd hours.
- Spending limits. If the provider supports budget caps or alerts, set them now.
- Access logs. For keys with data access (database, email, payment), look at what was read, sent or changed. A leaked email key can be used to send spam in your name; a leaked database admin key can expose customer data.
- Derived access. Did the key allow creating new keys, users or webhooks? Check for anything you did not create.
Minutes 40 to 60: Close the hole and write it down
- Remove the key from the code and move the call to the server (see the next section).
- Run the secret scanner again on the full history.
- If the repository was public, consider rewriting history with a tool such as
git filter-repo. This is cleanup, not protection: the old key must already be revoked, because copies may exist elsewhere. - Write a short note: what leaked, when you noticed, what you rotated, what the logs showed.
If personal data may have been accessed, data protection laws such as GDPR and Thailand's PDPA can require you to notify authorities or affected people within a short time frame. This is general information, not legal advice; talk to your data protection officer or lawyer early.
Supply chain incidents are a related risk: a compromised dependency can read environment variables at build time. Our write-up on the Axios supply chain attack explains how that works and what to check.
Moving secrets to the server side properly
The lasting fix is simple in principle: the browser talks to your server, and only your server talks to the paid API.
Browser -> your server route (checks login, limits) -> OpenAI / Stripe / email API
How this looks in practice:
- Next.js: a route handler or server action reads
process.env.OPENAI_API_KEYand returns only the result. - Nuxt: a file under
server/api/reads the private value fromuseRuntimeConfig()and calls the API. - Vite single-page apps: there is no server by default. Add one, for example a small backend, a serverless function or a Supabase Edge Function.
A server route alone is not enough. Without checks it becomes an open proxy to your paid API. Add at least:
- Authentication: only logged-in users can call it.
- Rate limits and per-user quotas: so one account cannot run up a large bill.
- Input validation: accept only what the feature needs, for example a message with a maximum length, not a free-form request body passed straight through.
- Narrow keys: where the provider supports scoped or restricted keys, give each key only the permissions it needs, and use separate keys for development and production.
When you work with an AI assistant, say this explicitly in the prompt: "Keep all API keys on the server. Never use a public environment prefix for secrets. Add authentication and rate limiting to the route." It is far easier to get this right from the start than to fix it later.
Frequently asked questions
My repository is private. Am I safe?
Only partly. A private repository protects the Git history, but anything in your frontend bundle is public the moment you deploy. Also think about who has access: former contractors, connected tools and old clones.
Is deleting the key from the code enough?
No. The key still exists in Git history, in old deployments and possibly in caches. Revoke it at the provider. That is the only step that actually stops misuse.
How do I know if someone used my leaked key?
Check the provider's usage, billing and audit logs for activity you do not recognize. If the provider offers no logs, assume it may have been used and act accordingly.
Should I rotate keys even without a leak?
Yes, on a regular schedule and whenever someone with access leaves the team. Rotation is much easier if keys live in one place, such as your hosting platform's environment settings or a secrets manager.
Can a scanner find every secret?
No. Scanners recognize known key formats and high-entropy strings, which catches most cases. Custom tokens, passwords in config files and secrets in logs can still slip through, so combine scanning with a manual review.
Get a second pair of eyes before launch
Exposed keys are a common finding in apps built with Cursor, Lovable, Bolt, v0, Replit or Claude Code, along with database rules and authentication gaps. If you would rather have this checked than check it yourself, our Vibe Code Check is a fixed-price security and code review of AI-built apps. We look at exposed secrets, public environment variables, server routes, database rules and auth, and give you a clear list of what to fix. Fixing is quoted separately, so you decide what to do with the findings.