# OpenAI API key exposed in client-side code: how to fix it

Canonical: https://caelo.sh/guides/openai-api-key-exposed-frontend
Published: 2026-11-27 · Updated: 2026-11-27 · Arthi Arumugam, Caelo by Irth Labs

**Short answer:** Assume the key is stolen. OpenAI's key safety guidance says never to deploy a key in client-side environments like browsers or mobile apps, because anyone can read it from your JavaScript. Revoke it in the OpenAI dashboard, create a new project key, move every OpenAI call to a server route and set a project spend limit with enforcement turned on.

## How does the key end up in the browser?

- It sits behind a public prefix: `VITE_OPENAI_API_KEY`, `NEXT_PUBLIC_OPENAI_API_KEY`, `EXPO_PUBLIC_OPENAI_API_KEY`.
- The OpenAI SDK is used in browser code with `dangerouslyAllowBrowser: true`. The openai-node README says browser use is disabled by default "to avoid exposing your secret API credentials", and this flag turns that protection off.
- The key is pasted straight into a component while prototyping and never moved.

## The vulnerable pattern and the fix

Vulnerable: the SDK runs in the browser with your key

```ts
import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: import.meta.env.VITE_OPENAI_API_KEY,
  dangerouslyAllowBrowser: true, // the SDK refuses browsers unless you set this
});
```

Fixed: a server route holds the key and checks the caller

```ts
// app/api/chat/route.ts (Next.js, runs on the server)
import OpenAI from "openai";

const openai = new OpenAI(); // reads OPENAI_API_KEY from the server environment

export async function POST(req: Request) {
  const userId = await getSignedInUserId(req); // your own auth check
  if (!userId) return new Response("Sign in first", { status: 401 });

  const { message } = await req.json();
  const response = await openai.responses.create({
    model: "gpt-4.1-mini",
    input: String(message).slice(0, 4000),
    max_output_tokens: 500,
  });
  return Response.json({ text: response.output_text });
}
```

`getSignedInUserId` stands for whatever your auth library provides. Without that check, the route is a free proxy to your OpenAI account. Add a rate limit too; see the rate limiting guide linked below.

## Fix it, step by step

1. Revoke the exposed key on the API keys page of the OpenAI platform and create a new one. OpenAI's guidance is to rotate a compromised key and contact support if you see usage you did not make.
2. Create the new key inside a project. OpenAI says a key created within a project is scoped to that project, and you can give it restricted permissions with only the endpoints it needs.
3. Set a project spend limit and turn on "Enforce a hard limit". OpenAI says a spend limit alone can monitor spending without stopping requests, and that enforcement is not instantaneous, so spending can slightly exceed the limit.
4. Move every OpenAI call into a server route, server action or edge function, and delete the public variable and the `dangerouslyAllowBrowser` flag.
5. Require a signed-in user and add a per-user rate limit on the route.
6. Check the usage page for requests you did not make, then rebuild, redeploy and search the new build for `sk-`.

## Will OpenAI or GitHub catch the leak for me?

Sometimes, and only for keys pushed to a public GitHub repository. GitHub's 2021 changelog says OpenAI is a secret scanning integrator and leaked keys in public repositories "are forwarded to the relevant service, who will automatically disable them and notify their owners." A key inside a deployed JavaScript bundle is never pushed to GitHub, so nothing scans it there.

## Check it automatically

Caelo flags OpenAI keys written in any project file, including the newer `sk-proj-`, `sk-svcacct-` and `sk-admin-` formats (`secrets.openai`), and an OpenAI key name behind a browser prefix (`browser.public-secret-name`). It runs on your machine and prints only a redacted form of each key. It does not look for `dangerouslyAllowBrowser`; search for that flag yourself.

- [Install Caelo: npx caelo . or the MCP server](/)
- [How Caelo compares with gitleaks, TruffleHog, Semgrep and others](/compare)

## Check your own app

1. Run the free local check: `npx caelo .` Caelo is a free, open source (MIT) command line tool and MCP server from Irth Labs that checks the files of an AI-built app for exposed API keys, Supabase and Firebase misconfigurations and `.env` files with real values. It runs on your machine, uploads nothing and uses no AI model. Each finding comes with a plain-English fix.
2. Follow the fix in the report and rerun Caelo. For an untracked, unignored file containing secrets, preview the US$19 quick fix. https://caelo.sh/fix
3. For an engineer's assessment, book the US$490 App Health Check. Irth Labs delivers a report and fixed repair quote, with credit toward the repair. https://www.irthlabs.com/start?service=app-health-check

## Questions

### Can I hide the key in an environment variable in a React or Vite app?

No. Anything a browser-only app can read, a visitor can read. Environment variables only stay secret when they are read by code that runs on a server.

### Is a spend limit enough protection?

No. It limits the damage, but OpenAI says the hard limit is not instantaneous, and a stolen key can still drain the budget up to the limit. Keep the key on a server so it is never stolen in the first place.

### Is dangerouslyAllowBrowser ever OK?

Only when each user supplies their own key, or for a throwaway prototype that never leaves your machine. With your own key in a deployed app, it hands the key to every visitor.

### I deleted the key from the code. Do I still need to revoke it?

Yes. Every deployment built with it, every browser cache and anyone who copied it still has the old key. Revoking is the only step that makes it useless.

## Sources

- [OpenAI Help Center: Best practices for API key safety.](https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety)
- [OpenAI Help Center: Managing projects in the API platform (project keys and spend limits).](https://help.openai.com/en/articles/9186755-managing-projects-in-the-api-platform)
- [openai-node README (browser support and dangerouslyAllowBrowser).](https://github.com/openai/openai-node)
- [GitHub changelog: RubyGems, Adobe and OpenAI are now GitHub secret scanning integrators.](https://github.blog/changelog/2021-06-08-rubygems-adobe-and-openai-are-now-github-secret-scanning-integrators)
- [Caelo source: every rule in lib/rules.js.](https://github.com/arthi-arumugam-git/caelo/blob/master/lib/rules.js)

## Related guides

- [I leaked an API key or the Supabase service_role key. What do I do now?](https://caelo.sh/guides/leaked-api-key-what-to-do)
- [Security checklist for apps built with Lovable, Bolt, Cursor, Replit or v0](https://caelo.sh/guides/vibe-coded-app-security-checklist)
- [Is my Cursor app secure? What Cursor protects and what it does not](https://caelo.sh/guides/is-my-cursor-app-secure)
- [How to rate limit API routes in an AI app, and cap your model bill](https://caelo.sh/guides/rate-limit-ai-app-api-routes)
- [Are VITE_ environment variables safe for API keys?](https://caelo.sh/guides/vite-env-variables-exposed)
