Teardown
Exposed API keys in frontend code: how to find and fix them
A teardown of our own Next.js demo app, which ships an LLM API key in its client bundle: how to find the key in the build, rotate it, move the call behind an authenticated, rate-limited route, and add secret scanning to CI.
- Published
- Updated
- 9 min read
- By Dev Talan
Key takeaways
The short version. Each point is explained in full below.
- 01
After the build, the variable name is gone. Search the build output for the provider's hostname and for key prefixes such as
sk-proj-,sk_live_, andsb_secret_. - 02
Check the provider's usage logs first, deploy the server route with a new, narrower key, then revoke the old key with an expiry of now. Removing it from the code leaves copies in old deployments, caches, and git history.
- 03
Give the server route four checks: a session check that answers 401, a per-user rate limit that answers 429, input validation with a length cap, and a model and output cap fixed on the server.
- 04
Publishable keys, such as Stripe
pk_keys or Supabase publishable keys behind row-level security, are designed for the browser, while secret keys, LLM keys, and database credentials are not. - 05
Secret scanning should run at push, on every pull request, and against the built bundle, together with an allowlist of public variable names, because keys set in a hosting dashboard never appear in git.
Exposed API keys in frontend code often come from a public environment variable prefix, such as VITE_ in Vite or NEXT_PUBLIC_ in Next.js. The build writes the value into JavaScript that every visitor downloads and can read. The fix is to rotate the key, move the call behind an authenticated, rate-limited server route, and add secret scanning to CI.
To show the bug and the fix in real code, we wrote a small demo for this article: a Next.js app that summarizes support tickets with an LLM API. No company or client code is involved, and the same mistake and fix apply to a Vite single-page app.
Calling a provider straight from the browser is a common pattern in apps built fast, often because the first version had no backend at all. That is a fair trade for a prototype. Once real users and a billing account are attached, it becomes one of the common gaps in AI-generated code to fix first.
How does an API key end up in a JavaScript bundle?
#An API key ends up in a JavaScript bundle when client code reads it from a public environment variable. The build tool replaces each reference with the literal value, so the key ships as plain text inside a file any visitor can open.
Both frameworks document this. The Vite guide to env variables says VITE_* variables should not contain sensitive information such as API keys. The Next.js guide to environment variables explains that a NEXT_PUBLIC_ value is inlined, during next build, into any JavaScript sent to the browser. Other tools use other prefixes with the same effect: EXPO_PUBLIC_ in Expo, PUBLIC_ in Astro and SvelteKit, and REACT_APP_ in Create React App.
This is the demo before the fix. A client component imports the function, so the key travels to the browser with it.
export async function summarizeTicket(ticketText: string): Promise<string> {
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-6-luna',
messages: [
{ role: 'developer', content: 'Summarize this support ticket in two sentences.' },
{ role: 'user', content: ticketText },
],
}),
});
const completion = await response.json();
return completion.choices[0].message.content;
}It works on the first try, which is why it survives a quick review. After the build, the variable name is gone and only the value remains, so searching the bundle for NEXT_PUBLIC_OPENAI_API_KEY finds nothing. You have to search for the value.
A gitignored .env file does not protect a public variable
Keeping .env out of git keeps the key out of the repository. It does nothing for the bundle. If the variable has a public prefix, the build writes its value into JavaScript whether it came from a local file or your hosting dashboard. To share configuration without values, EnvSift, our open source .env toolkit from Damn Labs, generates a .env.example template with the values removed.
Which API keys are safe in frontend code?
#A key is safe in frontend code only when the provider designed it to be public and something else enforces access. Publishable keys identify your account. Secret keys act on your behalf, spend money, or read data, so they belong on a server.
| Key | Safe in the browser? | What protects you |
|---|---|---|
Stripe publishable key, pk_live_ | Yes | Stripe limits it to creating tokens and payment methods. It cannot create charges or read account data |
Stripe secret or restricted key, sk_live_ or rk_live_ | No | Keep it on the server, prefer a restricted key, and attach an access policy that limits it to your servers |
Supabase publishable key or legacy anon key | Yes | Row-level security enabled on every table, with tested policies |
Supabase secret key or legacy service_role key | No | It bypasses row-level security, so it stays on the server |
Firebase web config apiKey | Yes | Security Rules and App Check, with the key restricted to Firebase APIs. A Gemini Developer API key is different and must stay secret |
| LLM provider keys, such as OpenAI, Anthropic, or Gemini | No | A server route with auth and rate limits, plus a spend limit at the provider |
| Email, SMS, and database credentials | No | Server-only environment variables or a secrets manager |
The official OpenAI JavaScript SDK makes the point itself: it refuses to run in a browser unless you pass dangerouslyAllowBrowser: true. If a codebase sets that flag, treat it as a finding. LLM keys deserve the closest look, since GitGuardian's State of Secrets Sprawl 2026 report found 81% year-over-year growth in leaked secrets for AI-related services.
How do you find exposed API keys in frontend code?
#Build the app, then search the output for key patterns and for the provider's hostname. A clean client bundle never mentions the provider's API domain, because the browser should only talk to your own server.
- 01Build what you deployRun the production build with the same environment variables your host uses. Next.js writes client code to
.next/static. Vite writes it todist, and also replaces%VITE_*%placeholders inindex.html, so search the whole folder. - 02Search for values, not namesSearch for the provider's hostname and for known key prefixes. OpenAI project keys start with
sk-proj-, Stripe live secret keys withsk_live_, Supabase secret keys withsb_secret_, and AWS access key IDs withAKIA. - 03Scan the build folderRun a secret scanner such as Gitleaks over the build output. It knows many key formats, so it also catches keys nobody knew were there.
- 04Check the live siteOpen the deployed app with the browser's developer tools open and trigger the feature. If the Network panel shows a request to the provider carrying an
Authorizationheader, the key is in the browser. Searching the loaded sources forBearerfinds the code that sends it.
pnpm build
grep -rl 'api.openai.com' .next/static
grep -rlE 'sk-proj-|sk_live_|sb_secret_|AKIA[0-9A-Z]{16}' .next/static
docker run --rm -v $(pwd):/repo ghcr.io/gitleaks/gitleaks:v8.30.1 dir /repo/.next/static --redact -vHow do you fix a leaked API key?
#Fix a leaked API key by revoking it at the provider and issuing a replacement. Removing it from the code is necessary but not enough. Old deployments, preview URLs, CDN and browser caches, and web archives can keep serving the old bundle, and anyone who already copied the key still has it.
Leaked keys also tend to stay live. GitGuardian's State of Secrets Sprawl 2026 report found that 64% of the valid secrets it detected in public repositories in 2022 were still active four years later. Revoking the key makes every copy worthless, and nothing else does.
- 01Check for abuse firstOpen the provider's usage or request logs for the period the key was public. If you see calls you did not make, revoke the key now and accept a few minutes of downtime.
- 02Create a narrow replacementIssue a new key with only the permissions the feature needs, such as a project-scoped LLM key or a Stripe restricted key. Set a spend limit or budget alert wherever the provider offers one.
- 03Store it on the serverAdd the new key to your host's secret store under a name with no public prefix, such as
OPENAI_API_KEY, in every environment that needs it. - 04Deploy the server routeShip the fix from the next section, then run the same bundle search to confirm the new build is clean.
- 05Revoke the old keyDelete or expire it at the provider. Stripe's dashboard rotation offers a grace period of up to 7 days in which both keys work. For a leaked key, choose an expiry of now.
- 06Write it downRecord what leaked, for how long, what it could reach, and what changed. A short written record makes the next security questionnaire easier to answer.
If the key was ever committed, GitHub's guide to removing sensitive data puts revoking or rotating the secret first and notes that rotation may be all you need. Rewriting history with git-filter-repo does not reach forks or other people's clones, and it breaks the diffs of pull requests that reference the removed commits. Save it for data that must disappear, such as customer records committed by mistake.
How do you move an API key to the backend?
#Move an API key to the backend by adding a server route that holds the key and calls the provider for the browser. The key lives in a server-only environment variable, and the browser calls your own endpoint instead of the provider.
A route that only forwards requests is an open proxy, and anyone with curl can spend your quota through it. The demo route does five things before and after it calls the provider.
- 01Checks the session and rejects anonymous callers with a 401.
- 02Rate-limits each user to 20 summaries an hour and answers with a 429 past that.
- 03Validates the body with Zod and caps the ticket at 8,000 characters.
- 04Fixes the model and reasoning effort on the server and caps output with
max_completion_tokens, so callers cannot pick an expensive model or a long answer. - 05Returns only the summary, and keeps the provider's raw response and errors on the server.
import { Ratelimit } from '@upstash/ratelimit';
import { Redis } from '@upstash/redis';
import { z } from 'zod';
import { getSession } from '@/lib/auth';
const summaryRequest = z.object({
ticketText: z.string().trim().min(1).max(8000),
});
const ratelimit = new Ratelimit({
redis: Redis.fromEnv(),
limiter: Ratelimit.slidingWindow(20, '1 h'),
prefix: 'ticket-summary',
});
export async function POST(request: Request): Promise<Response> {
const session = await getSession(request);
if (!session) {
return Response.json({ error: 'Sign in required' }, { status: 401 });
}
const { success } = await ratelimit.limit(session.userId);
if (!success) {
return Response.json({ error: 'Too many requests' }, { status: 429 });
}
const parsed = summaryRequest.safeParse(await request.json().catch(() => null));
if (!parsed.success) {
return Response.json({ error: 'Invalid request' }, { status: 400 });
}
const upstream = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-6-luna',
reasoning_effort: 'none',
max_completion_tokens: 200,
messages: [
{ role: 'developer', content: 'Summarize this support ticket in two sentences.' },
{ role: 'user', content: parsed.data.ticketText },
],
}),
});
if (!upstream.ok) {
return Response.json({ error: 'Summary unavailable' }, { status: 502 });
}
const completion = await upstream.json();
return Response.json({ summary: completion.choices[0].message.content });
}getSession stands in for your auth library's server-side session check. The limiter keeps its counters in Redis through Upstash, because counters held in one serverless instance's memory are not shared with other instances and reset when it restarts. Any shared store works, including Postgres or your host's own rate-limiting feature. Reasoning tokens count toward max_completion_tokens, so the route sets reasoning_effort to none to keep the whole budget for the summary.
export async function summarizeTicket(ticketText: string): Promise<string> {
const response = await fetch('/api/ticket-summary', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ticketText }),
});
if (!response.ok) {
throw new Error(`Summary failed with status ${response.status}`);
}
const { summary } = (await response.json()) as { summary: string };
return summary;
}The client now sends only the ticket text. With cookie-based sessions, the browser attaches the session cookie to same-origin requests by default, so the client needs no token handling. Any shared module that reads a secret, such as a provider client in lib/, should start with import 'server-only', which makes the Next.js build fail if a client component ever imports it.
What if the app has no server?
#A Vite single-page app has no server of its own, so the route becomes a serverless or edge function on your host, such as Vercel Functions, Netlify Functions, Cloudflare Workers, or Supabase Edge Functions. Vite's guide recommends the same move for any secret. The handler above uses the standard Request and Response objects, which these platforms accept with small changes, mostly in how the function is exported and how it reads environment variables.
How do you add secret scanning to CI?
#Add secret scanning at three points: before code is pushed, on every pull request, and against the built bundle. Each one catches a leak the others miss.
- At push. A Gitleaks pre-commit hook, or GitHub push protection where your plan includes it, stops a recognized key before it reaches the remote.
- On pull requests. A CI job scans the new commits, so a key that slipped past a local hook still fails the check.
- On the build. A key set in a hosting dashboard never touches git, so repository scanners cannot see it. Only a check on the build can.
name: secret-scan
on:
pull_request:
push:
branches: [main]
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: gitleaks/gitleaks-action@v3
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v7
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm build
- run: docker run --rm -v $(pwd):/repo ghcr.io/gitleaks/gitleaks:v8.30.1 dir /repo/.next/static --redact -vThe Gitleaks action needs a free license key for repositories owned by a GitHub organization, and none for personal accounts. The bundle scan only sees variables that exist in CI, so pair it with an allowlist of public variable names that runs inside every build, including the one on your host.
import { loadEnvConfig } from '@next/env';
const allowedPublicNames = new Set([
'NEXT_PUBLIC_APP_URL',
'NEXT_PUBLIC_POSTHOG_KEY',
'NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY',
]);
const hostSystemPrefix = 'NEXT_PUBLIC_VERCEL_';
loadEnvConfig(process.cwd());
const unexpectedNames = Object.keys(process.env).filter(
(name) =>
name.startsWith('NEXT_PUBLIC_') &&
!name.startsWith(hostSystemPrefix) &&
!allowedPublicNames.has(name),
);
if (unexpectedNames.length > 0) {
console.error(`Public variables missing from the allowlist: ${unexpectedNames.join(', ')}`);
process.exit(1);
}Add @next/env and tsx as dev dependencies and set the build command to tsx scripts/check-public-env.ts && next build. Vercel adds its own NEXT_PUBLIC_VERCEL_ system variables to preview and production builds, so the script skips that prefix. On another host, add its system variables to the list.
Adding a public variable now takes a deliberate change to the allowlist, and that change shows up in review, where someone can ask whether the value is meant to be public.
What should you do next?
#Run the bundle search on your own production build. It takes a few minutes and gives a definite answer. Then work through this list.
- The client bundle contains no provider API hostnames and no secret key patterns.
- Every variable with a public prefix is on a reviewed allowlist.
- Every leaked or suspect key has been revoked at the provider as well as removed from the code.
- Server routes that call paid APIs check the session, rate-limit each user, validate input, and cap output.
- CI scans pull requests and the built bundle, and a failed scan blocks the merge.
- Every paid API has a spend limit or budget alert at the provider.
The startup security checklist covers the other basics investors and enterprise buyers ask about, and the AI-built app risk checklist covers what else tends to break in AI-built apps.
If you want an outside review, a software audit checks secrets, authorization on every route, and input handling, backed by secret and dependency scans, and ends in a written report that ranks what to fix first.