---
title: "API keys: why they must never live in your front end"
description: "An API key in browser code can be read by anyone. Which keys are public, which are secret, and how to route calls through a server instead."
url: "https://vibe-code.blog/en/api-keys-security"
lang: "en"
author: "Thierry Gustin"
published: "2026-11-07"
updated: "2026-11-21"
---

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

> **Key takeaways** — Everything sent to the browser can be read by any visitor, including variables prefixed with VITE_ or NEXT_PUBLIC_. A secret key (OpenAI, Stripe sk_, Supabase service_role) placed in the front end can drain your credit or open your database. The rule: only keys designed to be public go on the client; everything else stays on a server or function that your app calls.

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**:

| Tool | Prefix exposed to the browser | What 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:

- **AI API key (OpenAI, Anthropic, Google)**: someone runs their own requests on your account until your credit or limit runs out.
- **Stripe secret key (`sk_live_`)**: Stripe describes it as having unrestricted permissions on all its APIs. Refunds, customer data, new charges.
- **Supabase `service_role` or `sb_secret_` key**: it bypasses every RLS policy. Full read, write and delete access to your database.
- **SMTP password or email sending key**: your domain gets used for spam, and your sender reputation suffers.

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:

| Service | Public key (front end allowed) | Secret key (server only) | What protects the public key |
| --- | --- | --- | --- |
| Supabase | `sb_publishable_...` or `anon` | `sb_secret_...` or `service_role` | Your RLS policies |
| Stripe | `pk_live_...` / `pk_test_...` | `sk_live_...`, `rk_live_...` | It cannot create charges or read account data |
| OpenAI, Anthropic | None | Every key | Nothing: never expose them |
| Stripe webhooks | None | `whsec_...` | 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.

> **The Supabase case** — The [Supabase](https://supabase.com/) public key visible in your code is not a vulnerability. What matters is your RLS policies. If they are missing, the public key is enough to read your database: the full story is in [Supabase RLS: the mistake that exposes your users' data](https://vibe-code.blog/en/supabase-rls-security).

## 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:

- a Supabase **Edge Function**, if your app is built with Lovable or Bolt plus Supabase;
- a Next.js **API route** or Server Action, if your app runs on [Vercel](https://vercel.com/);
- a Netlify **serverless function**;
- a small PHP script on shared hosting.

### Example: a Supabase Edge Function that calls OpenAI

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

```bash
supabase secrets set OPENAI_API_KEY=sk-...
```

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

```ts
// 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.

> **An open function is still a tap** — Moving the key to the server is not enough if anyone can call your function in a loop. Check that the user is signed in, cap request size, and set a spending limit with your API provider.

## 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](https://cursor.com/) or [Claude Code](https://www.anthropic.com/claude-code):

```text
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:

- Secret keys go in variables **without a public prefix**, read only by server code.
- On Vercel, pick the **Secret** type (write-only once saved) rather than Config for sensitive keys.
- Use a separate key per environment (test, production) and per service: if one leaks, you only cut that one.
- OWASP also recommends regular rotation and least privilege: with Stripe, prefer a restricted key (`rk_`) scoped to the operations you need over the full secret key.

For the full picture of what to check before opening your app, go back to the [pre-launch security checklist](https://vibe-code.blog/en/vibe-coding-security). For where to host your server functions, see [Vercel, Netlify or shared hosting](https://vibe-code.blog/en/deploy-vibe-coded-app), and to keep a clean history, [Git for vibe coders](https://vibe-code.blog/en/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

- [Env Variables and Modes — Vite](https://vite.dev/guide/env-and-mode)
- [How to use environment variables in Next.js — Next.js Docs](https://nextjs.org/docs/app/guides/environment-variables)
- [Best Practices for API Key Safety — OpenAI Help Center](https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety)
- [API keys — Stripe Docs](https://docs.stripe.com/keys)
- [Understanding API keys — Supabase Docs](https://supabase.com/docs/guides/api/api-keys)
- [Environment variables (Edge Functions) — Supabase Docs](https://supabase.com/docs/guides/functions/secrets)
- [Environment variables — Vercel Docs](https://vercel.com/docs/environment-variables)
- [About push protection — GitHub Docs](https://docs.github.com/en/code-security/secret-scanning/introduction/about-push-protection)
- [The State of Secrets Sprawl 2026 — GitGuardian](https://blog.gitguardian.com/the-state-of-secrets-sprawl-2026-pr/)
- [Secrets Management Cheat Sheet — OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html)

— Thierry Gustin, Formateur en intelligence artificielle (GustinAI) · November 21, 2026
