← Guides

OpenAI API key exposed in your frontend? Find it, rotate it, move it server-side (Cursor, Bolt, v0)

· PlugLeak

An OpenAI key in VITE_ or NEXT_PUBLIC_, or sent from the browser with dangerouslyAllowBrowser, is in the JavaScript visitors download. How to find it, revoke it, and call the API from a server route.

An OpenAI API key in frontend code is already public. Anyone who loads the site can save the JavaScript and read it. OpenAI says never to deploy a key in a browser or a mobile app: someone who takes it can make requests on your behalf, which may lead to unexpected charges or compromise of certain account data. Those requests should go through your own backend (Best practices for API key safety). The same leak shows up in apps built with Cursor, Bolt, and v0 when the key has a public env prefix or is imported into client code.

Why VITE_, NEXT_PUBLIC_, and the browser SDK ship the key

Vite exposes names that start with VITE_ in client source after bundling, and says to avoid that prefix so env variables are not leaked. In its example, import.meta.env.VITE_SOME_KEY is "123" and import.meta.env.DB_PASSWORD is undefined. VITE_* values should not contain API keys, because they are bundled into your source at build time. For production, Vite says to consider a backend server or a serverless or edge function (Env variables and modes). VITE_OPENAI_API_KEY is that case. Gitignore does not stop the inlining.

Next.js uses NEXT_PUBLIC_. Names without that prefix stay in Node and are not accessible to the browser. The prefix inlines the value at build time, replacing process.env.NEXT_PUBLIC_… with a hard-coded string in the client bundle. After next build, those variables stay at the value from the build environment (Environment variables). NEXT_PUBLIC_OPENAI_API_KEY ships. OPENAI_API_KEY does not, unless client code reads it.

A pasted string in a client file ships the same way. Next.js says Client Components must not access privileged data, and that passing an object into one exposes its fields. Only the data access layer should read process.env (Data security). See the NEXT_PUBLIC_ and VITE_ guide.

The OpenAI Node SDK disables browsers by default. It runs in the browser only if you set dangerouslyAllowBrowser to true, which the README says exposes secret API credentials in client-side code, where anyone who opens the page can inspect and reuse them (openai-node README). The call still goes to api.openai.com with the key in the page. Keep the key on a trusted server (Authentication). Cursor apps are often Next.js, Bolt apps are often Vite, and v0 warns on NEXT_PUBLIC_.

Search the live JavaScript

Open the deployed site. In DevTools, search Sources across the loaded files, or open a script in Network and search the response. Look for:

  • sk-. OpenAI API keys start with that prefix. Project keys start with sk-proj-.
  • VITE_OPENAI_API_KEY, NEXT_PUBLIC_OPENAI_API_KEY, and OPENAI_API_KEY.
  • dangerouslyAllowBrowser.

Check lazy-loaded chunks, not only the first file. Read the line before you treat a placeholder as a live key, and do not paste a match into a chat. The key may also still be in git history:

git log -S 'sk-' --all --oneline
git log -S 'VITE_OPENAI_API_KEY' --all --oneline
git log -S 'NEXT_PUBLIC_OPENAI_API_KEY' --all --oneline

Revoke the key, then check usage

Treat a key in the bundle as compromised. OpenAI says to rotate a leaked key immediately from the API Keys page and to update production apps to the new value: create a replacement, point the app at it, and revoke the old key once the replacement works (Best practices for API key safety). Deleting the source line does not revoke the key. A full secret is shown only when you create it. To delete a key, select the trash can icon next to it on the API key page. Deleted keys cannot be used (Where do I find my OpenAI API Key?).

On the Usage page, check that traffic matches your team's work. OpenAI says a compromised key can cause data loss, unexpected charges, a depleted monthly quota, and interrupted API access. Contact OpenAI through help.openai.com if you suspect misuse. Set monthly spend limits for the organization or project and enable hard enforcement. Spend alerts do not stop traffic. Hard enforcement can block legitimate requests, and spend may slightly exceed the limit because enforcement is not instantaneous. Project keys can expire, and administrators can set a maximum key lifetime in Platform settings.

Call OpenAI from a server route

Put the new key in OPENAI_API_KEY, with no public prefix. That is the name OpenAI recommends, so committed code does not contain the secret. Read it from a Next.js Route Handler or Server Action, a Vercel function, or a Supabase Edge Function. The browser calls /api/complete and never receives the key.

The Node SDK reads OPENAI_API_KEY when you construct the client with no arguments (Authentication). The model below is the one in the quickstart; keep the model your account should call. sessionUserId and isOverLimit are stand-ins for a 401 when there is no session and a 429 when that caller is over your limit.

// app/api/complete/route.ts
import OpenAI from "openai";

const client = new OpenAI();

export async function POST(request: Request) {
  const userId = await sessionUserId(request);
  if (!userId) return new Response("Unauthorized", { status: 401 });
  if (await isOverLimit(userId)) {
    return new Response("Too many requests", { status: 429 });
  }

  const body = await request.json();
  const input = typeof body.input === "string" ? body.input : "";
  if (!input) return new Response("Bad request", { status: 400 });

  const response = await client.responses.create({
    model: "gpt-6.2-astra",
    input,
  });

  return Response.json({ output: response.output_text });
}

The browser calls that route and never sees the key:

const res = await fetch("/api/complete", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ input: prompt }),
});
const data = await res.json();

An open /api/complete still lets anyone spend the key. The handler has to see the session. A page redirect does not (Cursor checklist).

On Bolt, keep the new key out of .env if browser code can read it. Secrets work only with server functions (also called edge functions). Bolt reads a secret when a server function needs it, and does not write it into project files, browser code, or the published site (Secrets). The Secrets page needs a connected database. Which values can stay in .env is in the Bolt environment variables guide. On v0, leave the key unprefixed and move the call server-side. The v0 checklist covers v0's NEXT_PUBLIC_ warning. A Vite app with no Next server can call OpenAI from a Supabase Edge Function that reads OPENAI_API_KEY. Do not prefix that name with VITE_. The NEXT_PUBLIC_ and VITE_ guide shows the function.

Rebuild, redeploy, and search again

Remove the client import, dangerouslyAllowBrowser, and the public env name. Rebuild and redeploy, then search the live JavaScript again for sk-, sk-proj-, and the old variable name. Next.js freezes NEXT_PUBLIC_ at next build, and Vite replaces import.meta.env at build time, so a dashboard edit does not change a bundle already shipped.

If git log listed the key, rotation is what stops it. Deleting the line leaves older commits, forks, and clones. Rewrite history only after the revoke. OpenAI says never to commit a key: a public repo can share it, and a private repo can still leak it in a breach. If a Claude Code command contained the key, check .claude/settings.local.json using the settings.local.json guide.

Scan the live URL

PlugLeak's free scan is a passive GET of the page and same-site JavaScript, and it stops at 25 files or 12 MB. It checks /.env, /.git/config, security headers, and TLS. It detects OpenAI, Anthropic, Stripe, and AWS keys, GitHub tokens, PEM private keys, sb_secret_ keys, and Supabase service_role JWTs.

It does not log in, crawl, query a database, or test Row Level Security. It does not read git history or server-only files.

Run it at https://plugleak.com/?utm_source=seo&utm_medium=article&utm_campaign=openai-key-frontend#scan. The scan is free. The fix report is $9, or $29 for 10. Prices are on the pricing section.

FAQ

Is VITE_OPENAI_API_KEY safe if .env is gitignored?

No. Vite bundles VITE_ variables into client source at build time and says they should not contain API keys. .gitignore does not stop that. Read OPENAI_API_KEY on the server, with no public prefix.

Does dangerouslyAllowBrowser keep the OpenAI key on the server?

No. The SDK disables browsers by default. dangerouslyAllowBrowser puts the key in client-side code, where anyone who opens the page can read it. Call api.openai.com from a server route.

I deleted the key from the frontend. Is the old key safe?

No. Rotate it on the API Keys page: create a replacement, update the app, and revoke the old key. Deleting the line does not revoke it, and git history can still hold a copy. Rotation is what stops the key.

Can the free scan see an OpenAI key that is only in git history?

No. The scan at https://plugleak.com/?utm_source=seo&utm_medium=article&utm_campaign=openai-key-frontend#scan is a passive GET of the public page and same-site JavaScript (max 25 files / 12 MB). It checks /.env, /.git/config, security headers, and TLS, and it detects OpenAI, Anthropic, Stripe, and AWS keys, GitHub tokens, PEM private keys, sb_secret_ keys, and Supabase service_role JWTs. It does not log in, crawl, query a database, test Row Level Security, or read git history.

Sources

Check your app now — free, passive, about 20 seconds.

Same scanner as the homepage scan. Paste the live URL. It reads what a visitor already downloads. It does not log in or query your database.