Security and shipping

API keys: why they must never live in your front end

Published Updated 7 min read

Read in : Français

Contents
  1. Why is everything in the front end public?
  2. What happens when a secret key leaks?
  3. Which keys can go in the front end, and which never?
  4. How do you call a paid API without exposing the key?
  5. Example: a Supabase Edge Function that calls OpenAI
  6. How do you check that your app exposes no keys?
  7. What should you do if a key has already leaked?
  8. Are environment variables enough?
  9. Frequently asked questions
  10. Frequently asked questions
  11. Sources

An API key in your front end is a house key taped to the front door. All code sent to the browser can be read by any visitor in two clicks. If your OpenAI key, your Stripe secret key or your Supabase service_role key is in there, someone will eventually find it. Here is which keys can be public, which never can, and how to route calls through a server.

Why is everything in the front end public?

The front end is the code that runs in your visitor's browser. To run it, the browser has to download it. Once downloaded, it can be read: open developer tools (F12), go to the Sources or Network tab, and search for the word key.

Minifying or "hiding" the code changes nothing. A key encoded in base64, split into pieces or stored in an innocent-looking variable can still be recovered: the browser has to reassemble it to send it.

The trap specific to vibe coding is environment variable prefixes:

ToolPrefix exposed to the browserWhat the docs say
Vite (Lovable, Bolt and many React apps)VITE_These variables are exposed in client code and should not contain API keys
Next.js (v0, many Vercel apps)NEXT_PUBLIC_The value is inlined into the JavaScript sent to the browser at build time

When the AI writes VITE_OPENAI_API_KEY into your .env, it has not secured the key; it has published it. The Vite docs say so plainly, and Next.js states that non-prefixed variables are only available on the server.

What happens when a secret key leaks?

A leaked secret key gives someone else your permissions, on your bill. The damage depends on the service:

This is not a fringe problem. GitGuardian's State of Secrets Sprawl 2026 report counts about 29 million secrets detected on public GitHub in 2025, including 1,275,105 AI service keys, up 81% year on year. The same report found that AI-assisted commits leaked secrets at roughly twice the baseline rate.

Which keys can go in the front end, and which never?

A key can go in the front end only if the vendor designed it for that and its permissions are limited by another safeguard. Here is the breakdown for the services most common in vibe coding:

ServicePublic key (front end allowed)Secret key (server only)What protects the public key
Supabasesb_publishable_... or anonsb_secret_... or service_roleYour RLS policies
Stripepk_live_... / pk_test_...sk_live_..., rk_live_...It cannot create charges or read account data
OpenAI, AnthropicNoneEvery keyNothing: never expose them
Stripe webhooksNonewhsec_...Nothing: it is a signing secret

For OpenAI, the official guidance leaves no room for doubt: never deploy your key in client-side environments like browsers or mobile apps, and route requests through your own backend.

How do you call a paid API without exposing the key?

The answer is always the same: the browser calls your server, and your server calls the API with the key. The key never leaves the server.

Depending on your stack, that "server" can be:

Example: a Supabase Edge Function that calls OpenAI

First, store the key as a function secret, never in the code:

supabase secrets set OPENAI_API_KEY=sk-...

Then the function reads the key on the server with Deno.env.get:

// supabase/functions/assistant/index.ts
Deno.serve(async (req) => {
  // 1. Reject calls with no signed-in user
  const auth = req.headers.get("Authorization");
  if (!auth) return new Response("Unauthorized", { status: 401 });

  // 2. Limit what the browser can send
  const { question } = await req.json();
  if (typeof question !== "string" || question.length > 2000) {
    return new Response("Invalid request", { status: 400 });
  }

  // 3. Call the API with the key stored on the server
  const r = await fetch("https://api.openai.com/v1/responses", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model: "MODEL_NAME", input: question }),
  });
  return new Response(await r.text(), { status: r.status });
});

The browser only sends the question. The model, the key and the limits are set on the server, so a malicious visitor cannot pick a pricier model or send a 500-page novel.

How do you check that your app exposes no keys?

The check takes ten minutes and covers three places: your code, the live site and your Git history.

  1. In the code: search for sk-, sk_live_, rk_live_, sb_secret_, service_role, whsec_ and API_KEY. Any hit in a front-end file, or in a VITE_ or NEXT_PUBLIC_ variable, is a problem.
  2. On the live site: open F12, go to the Sources tab, and run a global search (Ctrl+Shift+F, or Cmd+Option+F on a Mac) for the same patterns. That is what any visitor sees.
  3. In Git: make sure .env is in .gitignore and was never committed. A deleted file stays in the history.

This prompt does the sorting for you in Lovable, Bolt, Cursor or Claude Code:

List every key, token and secret used in this project.
For each one, state:
- the service it belongs to;
- whether the vendor's documentation designs it to be public or secret;
- where it is used (file, and front end or server);
- whether it is exposed to the browser (VITE_ or NEXT_PUBLIC_ prefix,
  hard-coded value, etc.).
For every exposed secret, propose moving the call into a server
function without changing the app's behaviour.
Do not change anything until I approve.

What should you do if a key has already leaked?

Treat an exposed key as compromised, even if you have seen no abuse. Deleting the file is not enough: the key may already have been copied.

  1. Revoke or rotate the key with the provider (OpenAI, Stripe, Supabase). Stripe offers rotation with a grace period of up to 7 days to avoid downtime.
  2. Replace it in your server or function environment variables, then redeploy. On Vercel, changes to environment variables only apply to new deployments.
  3. Review usage in the provider's dashboard: unusual requests, spikes in consumption, suspicious charges or refunds.
  4. Add guardrails: a hard spending cap with your AI provider (OpenAI recommends enforced limits, since alerts alone do not stop traffic), and push protection for secrets on GitHub.

On that last point, GitHub turns on push protection by default for personal accounts, blocking detected secrets from being pushed to public repositories. For organisation repositories, an admin has to enable it.

Are environment variables enough?

Environment variables only protect a key if they stay on the server. A VITE_ or NEXT_PUBLIC_ variable is an environment variable too, and it still ends up in plain text in the browser's JavaScript.

Good habits:

For the full picture of what to check before opening your app, go back to the pre-launch security checklist. For where to host your server functions, see Vercel, Netlify or shared hosting, and to keep a clean history, Git for vibe coders. If your app takes payments, the full setup is in Stripe in a vibe-coded app.

Frequently asked questions

Frequently asked questions

Is an API key in a .env file safe?

Only if that file is never sent to the browser and never committed to Git. The .env file itself is not public, but variables prefixed with VITE_ or NEXT_PUBLIC_ are inlined into your site's JavaScript at build time. A secret key must therefore sit in a variable without a public prefix, read only by a server function, and .env must be listed in .gitignore.

Can I hide my key by encoding or splitting it?

No. If the browser has to send the key to the service, it has to be able to reassemble it, so anyone else can too, by reading the code or watching requests in the Network tab. Base64 encoding, obfuscation or splitting barely slow down a curious visitor. The only real protection is keeping the key on a server the visitor never sees.

Can the Stripe publishable key go in my code?

Yes. Stripe says the publishable key (pk_live_ or pk_test_) can be included in front-end code or distributed apps. It powers Stripe.js and payment forms, but it cannot create charges or read account data. The secret key (sk_) and restricted keys (rk_), on the other hand, must never leave your server.

How can I tell whether someone else used my OpenAI key?

Open your account's usage dashboard and look for spikes, models you do not use or requests at unusual hours. If you have any doubt, rotate the key immediately and update your server. Then set a strict monthly spending limit, which OpenAI recommends on top of simple alerts, since alerts do not stop traffic.

Do Lovable or Bolt handle API keys correctly?

These tools offer ways to store secrets on the server, for example through Supabase Edge Function secrets. But if you paste a key into the chat or ask for a direct API call, the generated code may put it on the client. Check after every feature that calls a paid API, using the global search in your browser's developer tools.

Sources