← Guides

Anthropic API key (sk-ant-) in your JavaScript bundle? Delete it, check usage, move Claude calls server-side

· PlugLeak

An Anthropic key (sk-ant-) in VITE_, NEXT_PUBLIC_, or EXPO_PUBLIC_, or sent from the browser with dangerouslyAllowBrowser, is in the JavaScript visitors download. How to find it, delete it in Claude Console, and call Claude from the server.

An Anthropic API key in frontend code is already public. Anyone who loads the site can save the JavaScript and read it. Anthropic says your API key is a digital key to your account, and that someone who obtains and uses it incurs charges on your behalf (API key best practices). The Claude API docs say to call the API from your own back end, not from code that runs in your users' browsers, because anyone who uses a webpage can read a credential in that page's code (Authentication). The same leak shows up in apps built with Cursor, Bolt, v0, and Claude Code when the key has a public env prefix or the Anthropic SDK is constructed in client code.

Why VITE_, NEXT_PUBLIC_, and EXPO_PUBLIC_ ship the key

Vite exposes names that start with VITE_ in client source after bundling. To avoid leaking env variables to the client, avoid that prefix. In the docs, import.meta.env.VITE_SOME_KEY is "123" and import.meta.env.DB_PASSWORD is undefined. VITE_* variables should not contain sensitive information such as API keys, because the values 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_ANTHROPIC_API_KEY is that case. Gitignore does not stop the inlining.

Next.js uses NEXT_PUBLIC_. Names without that prefix stay in the Node.js environment 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 JavaScript sent to the browser. After the build, the app no longer responds to changes to those variables. They stay at the value from the environment where next build ran (Environment variables). NEXT_PUBLIC_ANTHROPIC_API_KEY ships. ANTHROPIC_API_KEY does not, unless client code reads it.

Expo inlines EXPO_PUBLIC_ the same way. When you run npx expo start, a reference such as process.env.EXPO_PUBLIC_API_URL is replaced with the value from the env file in the app bundle. Expo says not to store sensitive info, such as private keys, in EXPO_PUBLIC_ variables, because those variables are visible in plain text in the compiled application. When an end user runs the app, they have access to the code and the embedded environment variables (Environment variables in Expo). EXPO_PUBLIC_ANTHROPIC_API_KEY is in that bundle. The TypeScript SDK does not support React Native. A key in the Expo bundle is still readable.

A pasted string in a client file ships the same way. Next.js says Client Components must not access privileged data or server-only modules, and that only the data access layer should read process.env. By default, environment variables stay on the server. Next.js exposes a variable to the client when the name starts with NEXT_PUBLIC_ (Data security). Which names the bundler inlines is the NEXT_PUBLIC_ and VITE_ guide. An OpenAI key shipped the same way is the OpenAI frontend guide. A Stripe secret or a GitHub token shipped the same way is the Stripe frontend guide and the GitHub frontend guide.

Search the live site

Open the deployed site. In DevTools, search Sources across the loaded files, or open a script in Network and search the response. Also open the script URL with the browser's view-source. Check lazy-loaded chunks, not only the first file. If a script names a source map (sourceMappingURL), open that .map URL and search it too. Look for:

  • sk-ant-. The Get your Claude API key example uses that prefix. An Admin API key starts with sk-ant-admin. An Admin API key cannot call Claude. It manages the organization (Admin API, Authentication).
  • VITE_ANTHROPIC_API_KEY, NEXT_PUBLIC_ANTHROPIC_API_KEY, EXPO_PUBLIC_ANTHROPIC_API_KEY, and ANTHROPIC_API_KEY inside client code.
  • dangerouslyAllowBrowser and the request header anthropic-dangerous-direct-browser-access.

In Network, open a request to api.anthropic.com and read the headers. A direct HTTP request sends a Developer API key in Authorization: Bearer, or in the legacy x-api-key header. The docs say to send only one of those. Access tokens do not go in x-api-key (Developer API keys, API overview). The current TypeScript SDK puts an apiKey in Authorization: Bearer (client.ts). A search that only looks for x-api-key misses that call. The key is still in the page that built the header.

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-ant-' --all --oneline
git log -S 'VITE_ANTHROPIC_API_KEY' --all --oneline
git log -S 'NEXT_PUBLIC_ANTHROPIC_API_KEY' --all --oneline
git log -S 'EXPO_PUBLIC_ANTHROPIC_API_KEY' --all --oneline

Then run the free PlugLeak scan on the same URL. It is a passive GET of the page and same-site JavaScript. It does not start another batch of scripts once 25 files or 12 MB of JavaScript have been fetched. It checks /.env, /.git/config, security headers, and TLS. It detects Stripe, OpenAI, Anthropic, and AWS keys, GitHub tokens, PEM private keys, sb_secret_ keys, and service_role JWTs. The Anthropic shape it matches is sk-ant- when that prefix is not preceded by a letter, digit, or underscore, followed by at least 20 letters, digits, underscores, or hyphens. The match continues through every following character in that set. A shorter string does not match. A key that starts with sk-ant- is classified as Anthropic, not OpenAI. It does not download source maps. It does not test Row Level Security or grants, query a database, log in, crawl, or read git history, local files, or Claude Code sessions.

The scan is free, with no signup. Run it at https://plugleak.com/?utm_source=seo&utm_medium=article&utm_campaign=anthropic-key-frontend#scan. The fix report is $9, or $29 for 10. A full refund is available within 30 days of purchase, no questions asked (refund policy). Prices are on the pricing section.

What dangerouslyAllowBrowser and the browser header mean

The TypeScript SDK is for server-side TypeScript or JavaScript. Web browsers are disabled by default, to avoid exposing your secret API credentials. You enable that path by setting dangerouslyAllowBrowser to true. React Native is not supported. The option defaults to false. In a browser-like environment, the constructor throws unless you set it. The error says client-side use is disabled by default, as it risks exposing your secret API credentials to attackers, and shows new Anthropic({ apiKey, dangerouslyAllowBrowser: true }) (client.ts).

Setting the option does not move the key to a server. The TypeScript SDK guide says enabling it can expose your secret API credentials in client-side code, where anyone with access to the browser can inspect, extract, and misuse them. The same page names two cases where the risk can be lower: an internal tool used only by trusted users, and a short-lived development credential that is not also used in production, or that you rotate often. The key is still in the page in those cases.

A request sent directly from a browser is a cross-origin request. The API accepts one only when it includes anthropic-dangerous-direct-browser-access: true. The TypeScript SDK sends that header when dangerouslyAllowBrowser is true (Authentication). In the SDK, the header value is the string true (client.ts).

Some organization and workspace settings block browser requests even with that header. The list includes zero data retention (ZDR) and a customer-managed encryption key attached to a workspace. No Claude Console setting overrides the block. A blocked request returns a 401 authentication_error even though the credential is valid. The message begins CORS requests are not allowed for this Organization (Authentication, Errors). That 401 means the browser call was rejected. It does not mean the key left the bundle.

The header rule and the block apply to requests that include an Origin header. Browsers add that header. Server-side HTTP clients normally do not. If your backend passes on a request that started in the browser, create a new request to the Claude API. A forwarded request keeps the browser's Origin header, so the API treats it as a browser request (Authentication).

Delete the key, then check Usage and Logs

Treat a key in the bundle as compromised. Anthropic says to revoke it immediately (What should I do if I suspect my API key has been compromised?):

  1. Log in to your Claude Console account.
  2. Open the API keys page at platform.claude.com/settings/keys.
  3. Click the menu (the three horizontal dots) next to the exposed key.
  4. Select Delete API key.

Deleting the source line does not do this. The best practices article also says GitHub secret scanning looks for Claude API keys in public repositories. When GitHub finds one, it notifies Anthropic, Anthropic deactivates that key, and the account owner gets an email. A key that is only in the JavaScript your site sends to visitors is outside that description. Delete it on the API keys page anyway.

Then click Create key on the same page. Save the new value in a secrets manager, and keep it out of version control. The create flow names the key and sets an expiration you cannot change later, who the key acts as, and whether it is scoped to one workspace or to the organization. A key scoped to the organization needs the anthropic-workspace-id header on each Claude API request (Get your Claude API key, Developer API keys). Use a separate key for development, testing, and production when you can, so you can disable the one that leaked (API key best practices). If suspicious API activity continues, contact Anthropic Support. The compromised-key article says to do that.

On Usage and Logs, review traffic for the key. Those are the two pages the best practices article names.

The same article splits limits by organization type. For a custom rate limit organization, set spend limits on the Billing page and workspace rate limits on the Rate limits page. The article says those limits are a safeguard against unexpected usage from a leaked key or an errant script. For a standard rate limit organization, turn on auto-reload on the Billing page. Auto-reload charges the card on file when usage credits hit a threshold you set. The article says to consider that threshold carefully: it keeps the service running, and it is also the safeguard against unexpected usage from a leaked key.

The Workspaces page documents a monthly spend limit per workspace. Open Spend limits, and under Workspace limits select the workspace. Then click Set limit or Adjust limit next to Monthly spend limit. A workspace limit can keep that workspace below the organization's limits. It cannot raise them. If you do not set one, the workspace uses the organization's limits, and organization-wide limits still apply when workspace limits add up to more. A spend limit on the default workspace might not count or stop some usage in that workspace, including the Claude Console playground, Claude Managed Agents sessions, and Claude Code or Claude Desktop when a member signs in with a Claude Console account and uses the default workspace. The organization's spend limit still applies to that usage.

Call Claude from the server

Put the new key in ANTHROPIC_API_KEY, with no VITE_, NEXT_PUBLIC_, or EXPO_PUBLIC_ prefix. That is the name in Anthropic's env example, and the name the SDK reads when you construct the client with no arguments (API key best practices, TypeScript SDK). If you keep secrets in a local .env, add that file to .gitignore. In a cloud host, use the host's secret storage. The browser calls your route and never receives the key.

The model below is the one in the SDK getting started, claude-opus-5-5. Keep the model your account should call. max_tokens: 1024 is the value in that example. A response's content is an array of blocks (Messages API). 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 Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

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 message = await client.messages.create({
    max_tokens: 1024,
    messages: [{ role: "user", content: input }],
    model: "claude-opus-5-5",
  });

  return Response.json({ content: message.content });
}

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. The Cursor checklist is that check for Route Handlers. On v0, leave the key unprefixed and move the call to a Route Handler or Server Action. The v0 checklist covers v0's NEXT_PUBLIC_ warning.

A Vite app has no Next.js route handler. Put the call in a backend server or a serverless or edge function that reads ANTHROPIC_API_KEY from the host's server environment. Do not prefix that name with VITE_ (Env variables and modes). The function below is a new request to https://api.anthropic.com/v1/messages. It does not forward the browser request, so it does not copy the browser's Origin header. The headers are the ones in the Messages API example: x-api-key, anthropic-version: 2026-10-21, and content-type: application/json. There is no anthropic-dangerous-direct-browser-access header. sessionUserId is the same stand-in as above.

// supabase/functions/complete/index.ts — not part of the Vite build
Deno.serve(async (req) => {
  const userId = await sessionUserId(req);
  if (!userId) return new Response("Unauthorized", { status: 401 });

  const key = Deno.env.get("ANTHROPIC_API_KEY");
  if (!key) return new Response("Server misconfigured", { status: 500 });

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

  const res = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": key,
      "anthropic-version": "2026-10-21",
      "content-type": "application/json",
    },
    body: JSON.stringify({
      model: "claude-opus-5-5",
      max_tokens: 1024,
      messages: [{ role: "user", content: input }],
    }),
  });

  return new Response(await res.text(), {
    status: res.status,
    headers: { "content-type": "application/json" },
  });
});

On Bolt, keep the new key out of .env if browser code can read it. Environment variables live in the project .env file, and code that runs in the browser can read them. 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. Open the project, click the database icon, then Secrets. The Secrets page needs a connected database. Bolt says not to paste secret values into project code (Secrets). Which values can stay in .env is the Bolt environment variables guide.

Rebuild, redeploy, and search the live JavaScript

Remove the client import, dangerouslyAllowBrowser, and the public env name. Rebuild and redeploy. 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. Expo inlines EXPO_PUBLIC_ when the app bundle is built. Confirm on the live site, not in your editor. Load the deployed URL, search the script responses for sk-ant-, and hard-refresh so you are not looking at a copy the browser kept. A cache in front of the site can keep serving the previous JavaScript until a new request returns the new files. The old key is gone from the public bundle only when that live response no longer contains it.

Run the free scan again. A deleted key that is still in the JavaScript still matches the scan until visitors load a build without that string. If the replacement was written into the same public variable, it is exposed too.

If git log listed the key, deleting it in the Console is what stops it. Deleting the line leaves older commits, forks, and clones. If a Claude Code command contained the key, check .claude/settings.local.json using the settings.local.json guide. The live-URL scan cannot see that file.

FAQ

Is VITE_ANTHROPIC_API_KEY, NEXT_PUBLIC_ANTHROPIC_API_KEY, or EXPO_PUBLIC_ANTHROPIC_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. Next.js inlines NEXT_PUBLIC_ into the browser bundle at build time. Expo replaces EXPO_PUBLIC_ references in the app bundle and says those variables are visible in plain text in the compiled application. .gitignore stops a commit. It does not stop that inlining. Read ANTHROPIC_API_KEY on the server, with no public prefix.

Does dangerouslyAllowBrowser keep the Anthropic key on the server?

No. The TypeScript SDK disables browsers by default, because client-side use risks exposing your secret API credentials. Setting dangerouslyAllowBrowser to true lets the client run in the browser and sends the header anthropic-dangerous-direct-browser-access: true. The key is still in the page. Call the Claude API from your own backend.

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

No. Deleting the line does not delete the key. In Claude Console, open the API keys page, use the three-dot menu next to that key, and select Delete API key. Then create a new key and store it only where server code can read it. A copy can still sit in git history, in a CDN cache of the old bundle, and in .claude/settings.local.json.

Does Anthropic already deactivate a key that is only in my website's JavaScript?

The API key best practices article describes a different case. GitHub secret scanning notifies Anthropic when a Claude API key is in a public repository, and Anthropic deactivates that key. A key that reached visitors only through the JavaScript a deployed site sends is not that case. Delete it on the API keys page.

Can the free scan see an Anthropic key that is only in git history or a Claude Code session?

No. The scan at https://plugleak.com/?utm_source=seo&utm_medium=article&utm_campaign=anthropic-key-frontend#scan is a passive GET of the public page and same-site JavaScript. It does not start another batch of scripts once 25 files or 12 MB of JavaScript have been fetched. It checks /.env, /.git/config, security headers, and TLS. The Anthropic shape it matches is sk-ant- when that prefix is not preceded by a letter, digit, or underscore, followed by at least 20 letters, digits, underscores, or hyphens. A shorter string does not match. It also detects Stripe, OpenAI, and AWS keys, GitHub tokens, PEM private keys, sb_secret_ keys, and Supabase service_role JWTs. It does not test Row Level Security or grants, query a database, log in, crawl, read git history, or read local files or Claude Code sessions.

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.