Deutsch
GuideSecurity · Secrets

API keys in AI-built apps: what is safe in the frontend and what is not

Which keys may sit in browser code and which must stay on the server: Supabase publishable vs secret keys, VITE_ variables, OpenAI, Anthropic and Stripe keys.

By Tim GeithnerPublished 12 min read

Short answer

Everything in your frontend is public, including every VITE_ variable your code reads. Only keys that are designed to be public belong there: your Supabase URL and publishable (or legacy anon) key, protected by row level security, and your Stripe publishable key. Supabase secret and service_role keys, Stripe secret, restricted and webhook keys, and OpenAI or Anthropic keys stay on the server, in edge function secrets, and the browser calls your function instead.

Ask an AI about this page:ChatGPTClaude

On this page

Key takeaways

  • Everything that reaches the browser is public: the JavaScript bundle, every VITE_ variable it reads and every response your functions send.
  • Two kinds of keys are made for the browser: the Supabase URL with the publishable (or legacy anon) key, and the Stripe publishable key. They are safe only because the real rules live elsewhere, such as RLS.
  • Supabase secret and service_role keys bypass row level security. In the frontend, they turn every policy you wrote into decoration.
  • OpenAI, Anthropic and Stripe secret keys belong in edge function secrets. The browser calls your function; your function calls the provider.
  • A key that was ever in the bundle is leaked. Rotate it, don’t just delete the line.

Why is everything in the frontend public?

A Lovable, Bolt or Vite app is a bundle of JavaScript that every visitor downloads. Whatever that bundle contains, anyone can read: open the developer tools, look at the Sources tab or search the downloaded files. Minifying makes the code ugly, not secret. And every request the app makes, including its headers and the response, shows up in the Network tab.

This matters for API keys because of how Vite handles environment variables. Variables whose name starts with VITE_ are written into the bundle at build time. Vite’s own documentation is direct about it: such variables “will be exposed in client-side source code after Vite bundling”, and they should not hold sensitive data. The prefix is not a security feature. It’s an opt-in that says “this value may be public”.

So the question for every key in your project is simple: was it designed to be public? If yes, it may go into the frontend, and the system behind it has to enforce the rules. If no, it stays on a server, and the browser never sees it, not even for a moment.

Lovable says the same in its security best practices: secrets in frontend code are visible to users and “should be considered compromised”. Lovable also detects API keys pasted into chat and moves them into its Secrets store, which keeps them out of browser code.

Is the Supabase anon or publishable key a secret?

No. The publishable key, and the legacy anon key before it, is the key your Supabase client is created with, and it’s supposed to ship to every visitor. Supabase describes the publishable key as safe to expose online. Requests with it run as the Postgres role anon, or as authenticated once a user signs in, and those roles get exactly what your grants and row level security policies allow.

The secret key is the opposite. Like the legacy service_role key, it maps to the service_role role, and that role has the Postgres attribute BYPASSRLS. You can see the difference in any Supabase project:

The roles behind the keys
select rolname, rolbypassrls
from pg_roles
where rolname in ('anon', 'authenticated', 'service_role')
order by rolname;

In our test database, which sets up Supabase’s roles the same way, only service_role came back with rolbypassrls = true. The same query with the same data showed the practical effect: the public key’s role got zero rows from an owner-only table, a signed-in user got their own row, and service_role got every row.

That leads to the real question behind “is my anon key safe?”: what can that key reach today? This query lists every table in public, whether RLS is on and whether the anon role may read it:

What the public key can reach
select c.relname as table_name,
       c.relrowsecurity as rls_enabled,
       has_table_privilege('anon', c.oid, 'select') as anon_can_read
from pg_class c
join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public'
  and c.relkind in ('r', 'p')
order by c.relname;

A row with anon_can_read = true and rls_enabled = false is a table anyone with your public key can read in full. With Supabase’s default grants, that is every new table created without RLS. Fix those first: see table without RLS.

Legacy and new Supabase keys: how to tell them apart

Supabase has two generations of API keys, and many AI-built projects still use the older ones.

KeyLooks likePostgres roleIn the browser?
Publishable keysb_publishable_…anon or authenticatedYes
Legacy anon keya long JWT starting with eyJanon or authenticatedYes
Secret keysb_secret_…service_roleNever
Legacy service_role keya long JWT starting with eyJservice_roleNever

The legacy keys look alike, which is how the wrong one ends up in a VITE_ variable. Both are JWTs whose middle part names the role. The dashboard’s Settings → API Keys page tells you which is which. If you only have the string, decode it locally in your browser console, never on a website:

Which role is this legacy key? (run locally)
const key = "eyJ…"; // paste the key here
JSON.parse(atob(key.split(".")[1].replace(/-/g, "+").replace(/_/g, "/"))).role;
// "anon" is public, "service_role" is a secret

Four facts from Supabase’s documentation, checked on December 3, 2026:

  • Creating new keys does not revoke the legacy ones. Both sets work in parallel until you disable the legacy keys in the dashboard.
  • Supabase is deprecating the legacy anon and service_role keys in early 2027 and recommends moving to publishable and secret keys before then.
  • Supabase refuses secret keys sent from a browser: it checks the request’s User-Agent and answers with 401. That protects you from your own app accidentally using it, not from an attacker who copied the key out of your bundle and uses it from any other tool.
  • You can create one secret key per backend component, so a leak only forces you to rotate one of them.

The decision table: safe in the browser?

WhatExampleSafe in the browser?Where it belongs
Supabase project URLhttps://xyz.supabase.coYesFrontend
Supabase publishable or legacy anon keysb_publishable_…Yes, with RLS on every tableFrontend
Supabase secret or legacy service_role keysb_secret_…NoEdge function secrets, server only
Database password or connection stringpostgresql://…NoServer only, never in an app
Stripe publishable keypk_live_…, pk_test_…YesFrontend
Stripe secret keysk_live_…NoEdge function secrets
Stripe restricted keyrk_live_…NoEdge function secrets
Stripe webhook signing secretwhsec_…NoWebhook handler only
OpenAI or Anthropic API keyanyNoEdge function secrets
Any key returned by your own function{ apiKey: … }NoNowhere: don’t return keys
Your own signing or HMAC secretanyNoServer only

Two rules cover the gaps in any table: a key that can spend money, read other people’s data or skip permission checks is secret. And a key that is only safe “because nobody will look” is secret too.

How secret keys end up in the frontend

The mistakes repeat. Here are the four we see most, three of them from our own deliberately broken test apps.

1. The admin page that needs “just one” privileged call. An AI builder is asked for an admin page that lists all users. Listing users needs admin rights, so it creates a second Supabase client with the service role key, read from a VITE_ variable:

Vulnerablesrc/lib/admin.ts
const SERVICE_ROLE_KEY = import.meta.env.VITE_SUPABASE_SERVICE_ROLE_KEY as string;

export const supabaseAdmin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
  auth: { persistSession: false, autoRefreshToken: false },
});

The page itself may be hidden behind a role check, but the module is part of the bundle that every visitor downloads. Anyone can copy the key and read, change or delete every row in your database. More in service_role key in the frontend and secret key in a VITE_ variable.

2. A hard-coded secret constant. A payments helper signs requests with a secret written directly into a src/lib file. If any React component imports that file, the constant ships to every browser. This is CWE-798 (opens in a new tab), use of hard-coded credentials.

3. A function that hands out the key. The AI provider key is correctly stored as an edge function secret, but the function returns it to the browser so the page can call the provider directly:

Vulnerablesupabase/functions/get-ai-key/index.ts
const apiKey = Deno.env.get("OPENAI_API_KEY");
return new Response(JSON.stringify({ apiKey, model: "gpt-4o-mini" }), { headers });

The secret store did its job; the function undid it. In our test app this function also had JWT verification switched off, so anyone on the internet could fetch the key.

4. Keys stored in a database table. Some apps keep provider keys in a settings table so they can be changed without a redeploy. With Supabase’s default grants and RLS off, the public key reads them:

VulnerableA settings table holding keys
create table public.app_settings (
  id int primary key default 1,
  openai_api_key text,
  stripe_secret_key text
);

In our test, the anon role read openai_api_key straight out of this table. Find columns like these in your own project:

Columns that look like they hold secrets
select table_name, column_name
from information_schema.columns
where table_schema = 'public'
  and column_name ~* '(api_?key|secret|token|password)';

The right home for these values is your edge function secrets. If a table must hold them for now, at least lock it so that only server code with the secret key can read it:

SafeLock the settings table
alter table public.app_settings enable row level security;
revoke all on table public.app_settings from anon, authenticated;

After this, both the public key and signed-in users got permission denied, and only service_role could read the row. Keys that already sat in that table should still be rotated.

Check your own app in ten minutes

List your environment variables

Open .env, .env.example and your hosting settings. Every name starting with VITE_ is public. If any of them contains SERVICE_ROLE, SECRET, PRIVATE, OPENAI, ANTHROPIC or a Stripe secret, that is a finding, whatever the value is today.

Search your source code

Search the src/ folder for service_role, sb_secret_, sk_live_, rk_live_, whsec_ and Deno.env (which should only appear under supabase/functions/). In Lovable you can ask the chat to run this search for you.

Search the built bundle

Build the app and search the output, because that is what visitors download. In your project folder:

Search your own build output
npm run build
grep -rlE "sb_secret_|sk_live_|rk_live_|whsec_" dist/

Any file listed is a lead to follow up. No output is good, but it only covers the patterns you searched for.

Read what your functions return

Open the app, then the Network tab, and click through every feature that calls an edge function. Look at each response body. A response should never contain a key, a token for a third-party service or another user’s data.

Run the two SQL checks

Run “What the public key can reach” and “Columns that look like they hold secrets” from above in the SQL editor. Fix every table that is readable by anon without RLS.

How do I call OpenAI or Anthropic without exposing the key?

Both providers say the same thing. OpenAI’s key safety guide: “Requests should always be routed through your own backend server”, never sent from a browser or mobile app. Anthropic recommends loading keys from environment variables or a secret manager and never sharing them. A leaked AI key is a direct line to your credit card: someone else’s traffic on your bill, until you notice.

In a Supabase app, the backend is an edge function. The browser sends the user’s request to your function; the function checks who is calling, applies your limits, calls the provider with the key from its secrets and returns only the answer. A shortened sketch, not a complete function:

Safesupabase/functions/suggest-itinerary/index.ts (sketch)
const token = req.headers.get("Authorization")?.replace(/^Bearer\s+/i, "") ?? "";
const userClient = createClient(SUPABASE_URL, SUPABASE_ANON_KEY, {
  global: { headers: { Authorization: `Bearer ${token}` } },
});
const { data } = await userClient.auth.getUser(token);
if (!data.user) return json({ error: "Not signed in" }, 401);

// Your own checks go here: plan, daily limit, input length.

const response = await fetch("https://api.openai.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${Deno.env.get("OPENAI_API_KEY")}`,
  },
  body: JSON.stringify({ model: "gpt-4o-mini", messages }),
});
const result = await response.json();
return json({ text: result.choices?.[0]?.message?.content ?? "" });

Three things make this proxy safe rather than just hidden:

  • It identifies the caller from the verified token, not from a userId in the body. Functions that trust the body are covered in edge function trusts user_id from the body.
  • It limits usage. Without a per-user limit, your proxy is a free AI endpoint for anyone with an account. See rate limiting for AI-built apps and no AI spend cap.
  • It returns only the result. Never the key, and not the provider’s raw response if it contains more than you need.

OpenAI also recommends monthly spend limits on the provider side, so a leaked key has a ceiling. Our guide on calling OpenAI or Anthropic safely goes through the full setup, and OpenAI or Anthropic key in client code is the short fix page.

What about Stripe keys?

Stripe’s key types map cleanly onto the browser question:

  • Publishable keys (pk_live_…, pk_test_…) are made for Stripe.js, Elements and mobile apps. Stripe says they can’t do sensitive things like creating charges or reading account data, and marks them as safe to deploy.
  • Secret keys (sk_…) have full access to your Stripe account. Stripe now recommends restricted keys instead, even on the server.
  • Restricted keys (rk_…) carry only the permissions you give them. Server only.
  • Webhook signing secrets (whsec_…) are not API keys, but they prove that a webhook came from Stripe. Anyone who has yours can send fake “payment succeeded” events.

In practice: the browser gets the publishable key and a client secret for the one payment it is completing; your edge function creates the payment with a restricted key and sets the price from server-side data, not from the request. Our Stripe security guide covers subscriptions and webhooks, and Stripe webhook without signature check shows the verification step.

I already shipped a secret key. What now?

Deleting the line and redeploying is not enough: old bundles stay in caches, and anyone who copied the key still has it. Assume it is in someone’s hands, rotate it and act in this order.

Rotate the key first

Supabase: create a new secret key, move your server code and edge functions to it, then delete the old secret key or disable the legacy keys. OpenAI and Anthropic: create a new key, update your function secrets, delete the old key. Stripe: roll the key in the dashboard; Stripe lets old and new keys overlap for up to 7 days so you can migrate without downtime.

Remove it from the code and the history

Move the value into your edge function secrets and remove every VITE_ variable that held it. If the key was committed, it is also in your git history; see secrets in git history.

Check what happened

Look at your provider usage pages and your Supabase logs for activity you don’t recognise. For a leaked Supabase secret key, check your tables for changes and new users. Our first 60 minutes after a leaked service_role key is a step-by-step runbook.

What our audit reports for this bug

We keep small, deliberately broken test apps to measure ShipRely’s audit engine. Two of them are about keys. The first has the admin client with the service role key from a VITE_ variable and a hard-coded signing secret in a payments helper. The second has the edge function that returns the AI key (with JWT verification switched off in its config) and a second function that reads any user’s trips by a userId from the request body with admin rights.

In our latest benchmark run (December 3, 2026), the engine reported the service role key in browser code as critical, the hard-coded signing secret as high, the key-returning function as critical and the body-trusting function as high. It also reported, as high, that the admin page was guarded only by a role check in the browser, which shares its root cause with the leaked key. It did not flag the publishable key in the normal Supabase client, which is correct, nor the Stripe client secret that the checkout function returns to the browser, which Stripe designed for exactly that. Telling the public keys from the secret ones is the point of the exercise. How we run these tests is on our methodology page.

A fix prompt for your AI builder

Paste this into Lovable, Cursor, Claude Code or Bolt and review the changes before you accept them:

Move every secret key out of the frontend

Find every API key, secret or token that is used in browser code in this project: any VITE_ variable that holds a Supabase service_role or secret key (sb_secret_), a Stripe secret, restricted or webhook key, an OpenAI or Anthropic key, or any hard-coded secret constant in src/. Also find edge functions that return a key or token in their response.

For each one, move the privileged call into a Supabase Edge Function that reads the key with Deno.env.get, verifies the caller with auth.getUser on the request’s Authorization header, never trusts a user id from the request body, and returns only the result. Keep only the Supabase URL, the publishable or anon key and the Stripe publishable key in frontend code.

Afterwards, list every key I need to rotate because it was exposed, and the exact secret names the edge functions now expect.

Checklist before you launch

API key checklist

0/9 done

Your progress is saved in this browser only.

Frequently asked questions

Is it safe to put my Supabase anon key in the frontend?

Yes. The anon key, and its successor the publishable key (sb_publishable_…), are designed to be public. They only identify your project and run requests as the anon or authenticated role. What they can reach is decided by your grants and row level security policies, so the key is only as safe as your RLS.

Are environment variables in Vite secret?

Not if they start with VITE_. Vite’s documentation says these variables are exposed in client-side source code after bundling. Use VITE_ only for values that may be public, and keep secrets in your backend or edge function secrets.

Can I hide an OpenAI key by fetching it from an edge function at runtime?

No. Once the key reaches the browser, anyone can read it in the network tab, no matter how it got there. The edge function has to make the AI call itself and return only the result, after checking who is calling.

What should I do if my service_role key was in my frontend?

Treat it as leaked. Remove it from the code, create a new secret key in the Supabase dashboard, move your server code to it, then disable the old legacy keys or delete the old secret key. Afterwards, check your data and logs for changes you didn’t make.

Is the Stripe publishable key safe in client code?

Yes. Stripe marks publishable keys (pk_live_… and pk_test_…) as safe to deploy in front-end code. Secret keys (sk_…), restricted keys (rk_…) and webhook signing secrets (whsec_…) are not, and belong on the server only.

Sources

  1. 1.Understanding API keys — Supabase Docs
  2. 2.Env Variables and Modes — Vite Docs
  3. 3.API keys — Stripe Docs
  4. 4.Best Practices for API Key Safety — OpenAI Help Center
  5. 5.API Key Best Practices: Keeping Your Keys Safe and Secure — Anthropic
  6. 6.Security best practices — Lovable Docs
  7. 7.CWE-798: Use of Hard-coded Credentials — MITRE

Find this in your own app

ShipRely reads your repository (read-only), proves each finding with file and line, and gives you a fix prompt to paste into your AI builder.

Run a demo audit
  • Read-only access to your repository
  • Every finding with file and line
  • Fix prompts for Lovable, Cursor, Claude Code and Bolt