Skip to content

Guide · 7 min read · Updated 28 November 2026

How API keys leak into front-end code, and how to fix it

The short answer

Anything in your web page's code can be read by anyone who opens the page. A secret API key belongs on a server: the browser should call your own server, and your server should call the provider. If a secret key was ever in your page, rotate it before anything else.

How keys end up in the page

Almost nobody pastes a secret into a web page on purpose. It usually happens in one of these ways:

  • A public environment variable. Front-end tools copy variables with certain prefixes into the code they ship: NEXT_PUBLIC_ in Next.js, VITE_ in Vite, REACT_APP_ in Create React App, PUBLIC_ in SvelteKit and Astro. Putting a secret there publishes it.
  • Calling the provider straight from the browser. A prototype or AI-generated snippet often calls an AI or payment API directly from the page, which only works if the key is in the page too.
  • A key left in a quick fix. A key hard-coded "just for testing" in a component, a config file or an inline script that then goes live.
  • The wrong key of a pair. Many providers issue a publishable key for browsers and a secret key for servers. Swapping them puts the secret one in the page.
# .env — the prefix decides who can read it

NEXT_PUBLIC_OPENAI_KEY=sk-...   # copied into the page: anyone can read it
VITE_STRIPE_SECRET=sk_live_...  # same in Vite
OPENAI_API_KEY=sk-...           # server only: stays on the server

Publishable keys are fine. Secret keys aren't.

Some keys are designed to be public. A Stripe publishable key (pk_live_) can only start a payment, not take money out. Google Maps and Firebase browser keys are expected in pages, but should be restricted to your own domain and to the APIs you use in the provider's console.

Secret keys are different. An AI provider key (OpenAI, Anthropic, Gemini and others), a Stripe secret key (sk_live_), or a GitHub, Slack or SendGrid token lets whoever holds it act as your account. That can mean running up an AI bill, issuing refunds, reading data or sending email as you.

How to check your site

  • Scan it. A free Scanetra scan reads your homepage's public code and reports any secret it recognises by type and location. It never shows or stores the value.
  • Search your build. The page you see is only part of what you ship. Search the built files for key formats before each release:
# After a production build, search the files you ship
grep -rEn "sk-(proj-|ant-)?[A-Za-z0-9_-]{20,}|sk_live_[A-Za-z0-9]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY" \
  .next/static dist build 2>/dev/null

A scan of the homepage won't see keys in scripts only loaded on other pages, so the build search is worth adding to your release steps.

If you find one: rotate first

  1. Revoke or rotate the key in the provider's console, straight away. Removing it from the page doesn't help if it has already been copied, and old versions of your page may be cached or archived.
  2. Look at its usage. Check the provider's usage, billing and log pages for activity you don't recognise, from the time the key went live.
  3. Then fix the code so the new key never reaches the page, as below.

The fix: call your own server

Move every call that needs a secret to server code: an API route, a serverless function or your back end. The key lives in a server-only environment variable. The page calls your route, and your route calls the provider.

// app/api/chat/route.ts — runs on the server, never in the browser
export async function POST(req: Request) {
  const { message } = await req.json();
  if (typeof message !== "string" || message.length > 2000) {
    return Response.json({ error: "Invalid message" }, { status: 400 });
  }

  const res = await fetch("https://api.openai.com/v1/responses", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, // server-only variable
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model: process.env.AI_MODEL, input: message }),
  });
  return Response.json(await res.json(), { status: res.status });
}
// In the page: call your own route, with no key in sight
const res = await fetch("/api/chat", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ message }),
});

Two things make this route safe to leave running:

  • Limit it. Without limits, your route becomes a free relay to your AI account. Add rate limits per visitor, cap the input size as above, and require sign-in if the feature is for your users only.
  • Set spending limits in the provider's console, so a mistake can only cost so much.

On Vercel, Netlify and similar hosts, add the key under the project's environment variables without a public prefix. Server routes can read it; the browser can't.

Stop it happening again

  • Turn on secret scanning and push protection for your repository. GitHub offers both, and blocks many known key formats before they're pushed.
  • Keep secrets out of the repository entirely: use a .env file that is git-ignored, or your host's secret settings.
  • Treat any variable with a public prefix as published, and review AI-generated code for direct calls to paid APIs from the browser.
  • Scan your site after each launch. Scanetra is free and needs no account.

Further reading

Check your own site

Check whether your homepage exposes a key, along with HTTPS, headers, cookies and malware signs.

Scan a website