# Exposed API keys in frontend code: how to find and fix them

URL: https://pixelactstudio.com/blog/exposed-api-keys

> Exposed API keys in frontend code, fixed in our own Next.js demo: find the key in the build, rotate it, move the call server-side, and add secret scanning.

By Dev Talan. Published 2026-11-01. Updated 2026-11-01. Type: Teardown.

## Key takeaways

- 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_`, and `sb_secret_`.
- 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.
- 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.
- 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.
- 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](https://pixelactstudio.com/blog/ai-generated-code-risks) 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](https://vite.dev/guide/env-and-mode) says `VITE_*` variables should not contain sensitive information such as API keys. The [Next.js guide to environment variables](https://nextjs.org/docs/app/guides/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.

```ts
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](https://pixelactstudio.com/work/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.

**Common keys and whether they can ship to the browser**

| 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](https://github.com/openai/openai-node) 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](https://www.gitguardian.com/state-of-secrets-sprawl-report-2026) 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.

1. **Build what you deploy.** Run the production build with the same environment variables your host uses. Next.js writes client code to `.next/static`. Vite writes it to `dist`, and also replaces `%VITE_*%` placeholders in `index.html`, so search the whole folder.
2. **Search for values, not names.** Search for the provider's hostname and for known key prefixes. OpenAI project keys start with `sk-proj-`, Stripe live secret keys with `sk_live_`, Supabase secret keys with `sb_secret_`, and AWS access key IDs with `AKIA`.
3. **Scan the build folder.** Run a secret scanner such as Gitleaks over the build output. It knows many key formats, so it also catches keys nobody knew were there.
4. **Check the live site.** Open 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 `Authorization` header, the key is in the browser. Searching the loaded sources for `Bearer` finds the code that sends it.

```bash
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 -v
```

## How 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](https://www.gitguardian.com/state-of-secrets-sprawl-report-2026) 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.

1. **Check for abuse first.** Open 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.
2. **Create a narrow replacement.** Issue 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.
3. **Store it on the server.** Add 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.
4. **Deploy the server route.** Ship the fix from the next section, then run the same bundle search to confirm the new build is clean.
5. **Revoke the old key.** Delete 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.
6. **Write it down.** Record 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](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository) 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.

1. Checks the session and rejects anonymous callers with a 401.
2. Rate-limits each user to 20 summaries an hour and answers with a 429 past that.
3. Validates the body with Zod and caps the ticket at 8,000 characters.
4. Fixes 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.
5. Returns only the summary, and keeps the provider's raw response and errors on the server.

```ts
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.

```ts
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.

```yaml
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 -v
```

The 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.

```ts
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](https://pixelactstudio.com/resources/startup-security-checklist) covers the other basics investors and enterprise buyers ask about, and the [AI-built app risk checklist](https://pixelactstudio.com/resources/ai-built-app-risk-checklist) covers what else tends to break in AI-built apps.

If you want an outside review, a [software audit](https://pixelactstudio.com/services/software-audits) 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.

## Frequently asked questions

### Can I hide an API key in the browser with obfuscation or encryption?

No. The browser has to turn the key back into plain text to send it, so anyone can read it in the Network panel or by pausing the script just before the request. Obfuscation slows a casual reader for a minute and stops nobody who wants the key. If a value must stay secret, the code that uses it has to run on a server you control.

### Is restricting a key by domain or HTTP referrer enough?

For keys built for the browser, such as a Google Maps key with website restrictions, referrer limits are the intended protection. They are weak for anything secret, because a script running outside a browser can send any `Referer` header it likes. For LLM, payment, email, and database keys, use a server route and keep referrer rules as an extra layer on top of it.

### Do Next.js Server Components keep API keys out of the browser?

Yes, as long as the key stays in server code. Server Components, Route Handlers, and Server Actions run on the server, so they can read variables without the `NEXT_PUBLIC_` prefix, and those values stay there. The risk is passing a secret into a Client Component as a prop. Props that cross that boundary are serialized into the page payload, so pass the result of the call and keep the key in server code.

### How can we tell whether a leaked key was used?

Check the provider's usage dashboard or request logs for the window between the first deploy that contained the key and the moment you revoked it. Look for unfamiliar IP addresses, models or endpoints your app never calls, and spikes outside your users' working hours. Stripe, for example, shows request logs for each key. If you find misuse, contact the provider and keep the logs with your incident record.

### Do we need a secrets manager, or are hosting environment variables enough?

For most seed-stage products, the encrypted environment variables on your hosting platform are enough, as long as production values are visible only to the people who deploy and secret names carry no public prefix. A dedicated secrets manager, such as AWS Secrets Manager, Doppler, or HashiCorp Vault, pays off when several services share credentials, when you need scheduled rotation, or when a customer asks for an audit trail of who read which secret.