← Blog

Anthropic API Key Security Best Practices

2026-11-11 · 5 min read · SubToAPI Team

An exposed Anthropic API key can mean unexpected usage charges, leaked prompts and completions, or a compromised production app if someone finds it in a public repo, a client-side bundle, or a leaked log file. The good news is that securing an Anthropic API key follows the same disciplines as securing any other secret — you just need to apply them consistently across storage, access, and monitoring.

This guide covers the concrete practices that actually reduce risk: where to store keys, how to scope and rotate them, how to keep them out of client code, and what to do if one leaks.

Never Put Keys in Client-Side Code

The single most common mistake is calling the Anthropic API directly from a browser or mobile app with the key embedded in the bundle. Any JavaScript shipped to a browser is readable by anyone, regardless of minification or obfuscation. If your key is in there, it's public.

The fix is architectural: your frontend should talk to your own backend, and your backend holds the key and forwards requests to the API. This also gives you a natural place to add rate limiting, user-level auth, and logging before a request ever reaches Anthropic.

// Backend route — key stays server-side
app.post("/api/chat", async (req, res) => {
  const response = await fetch("https://api.anthropic.com/v1/messages", {
    method: "POST",
    headers: {
      "x-api-key": process.env.ANTHROPIC_API_KEY,
      "anthropic-version": "2023-06-01",
      "content-type": "application/json"
    },
    body: JSON.stringify({ model: "claude-sonnet-4-5", max_tokens: 1024, messages: req.body.messages })
  });
  const data = await response.json();
  res.json(data);
});

Store Keys in Environment Variables, Not Source Control

Keys belong in environment variables or a secrets manager — never hardcoded in source files, config files committed to git, or Dockerfiles. Use a .env file for local development and add it to .gitignore immediately, before you add the key.

# .gitignore
.env
.env.local

For production, use your platform's secret store: AWS Secrets Manager, Google Secret Manager, Vercel/Netlify environment variables, or your CI provider's encrypted secrets. Avoid passing keys as command-line arguments — they end up in shell history and process lists visible to other users on shared machines.

If a key does end up in a git commit, rewriting history with git filter-repo or BFG Repo-Cleaner isn't enough — the key is compromised the moment it's pushed, even to a private repo. Revoke it and issue a new one.

Scope Keys by Environment and Team

Use separate keys for development, staging, and production. This limits blast radius: a leaked dev key with low usage limits is a minor incident, while a leaked production key with full spend potential is a serious one. It also lets you track usage and spending per environment without guesswork.

If multiple team members or services need access, avoid sharing one key across everyone. Shared keys make it impossible to tell who caused a spike in usage or who needs to be notified when rotating. If your current setup doesn't support per-user or per-service keys, this is a strong argument for a layer in front of the raw API, like SubToAPI, which issues individual sub_live_... application keys per app or team member while billing through a single Anthropic account. You get usage attribution and seat-level access control without building that infrastructure yourself — see /docs/quickstart.

Rotate Keys on a Schedule, Not Just After Incidents

Rotation shouldn't only happen in response to a leak. Build it into your routine:

A practical rotation pattern is to generate the new key, deploy it alongside the old one, confirm the new key works in production, then revoke the old key. This avoids downtime during the swap.

Limit What a Leaked Key Can Do

You can't fully prevent leaks, but you can limit their impact:

Secure Keys in CI/CD Pipelines

CI/CD systems are a common leak vector because keys are often injected as environment variables into build logs. Use your CI provider's "secret" variable type (which masks the value in logs) rather than a plain environment variable, and avoid printing environment variables for debugging in shared pipelines.

# GitHub Actions example
env:
  ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}

Double-check that your build scripts don't accidentally echo the full environment or write it to a log artifact that gets uploaded.

Have an Incident Response Plan Ready

Before you need it, know the steps for a leaked key:

  1. Revoke the key immediately in the Anthropic console.
  2. Issue a replacement key and redeploy affected services.
  3. Review usage logs for the leaked key to assess unauthorized activity.
  4. Check spending for the affected period and dispute or budget for unexpected charges.
  5. Audit how the leak happened (commit, log file, client bundle) and fix the root cause so it can't recur.

Simplify Key Management With a Gateway

If you're managing keys across multiple apps, environments, and team members, raw API key management gets harder to track over time. A gateway like SubToAPI sits between your apps and Anthropic, giving each app or developer its own sub_live_... key, centralized usage metadata, and team seat management — so revoking one application's access doesn't mean rotating a shared secret used elsewhere. Check /pricing for plan details or start with the free trial at /signup.

Questions

Is it safe to use the same Anthropic API key across dev, staging, and production? No. Use separate keys per environment so a leak or bug in one environment doesn't expose production spending limits or require rotating a key shared by every system.

What should I do immediately if I find an Anthropic API key in a public GitHub repo? Revoke the key in the Anthropic console right away, generate a replacement, redeploy any services using it, and review usage logs for unexpected activity during the exposure window.

Can I restrict an Anthropic API key to only certain IP addresses or usage limits? Check your Anthropic console for current spending and usage limit controls. If you need per-app or per-team-member key issuance and usage tracking beyond what the raw console offers, a layer like SubToAPI (/docs) adds that management layer on top.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →