AleannLab

Secret Keys Shipped in the Frontend: Which Keys Are Safe in the Browser?

AleannLab team3 min read

Everything in your JavaScript bundle can be read by anyone who opens your site. Minification and environment variables do not hide it. Some keys are built for that (Supabase publishable key, Stripe publishable key, Firebase config). Others give full access to your data or your bill (Supabase secret key, Stripe secret key, OpenAI or Anthropic keys). If one of the second kind is in the bundle, rotate it first and move the call to a server route after.

On this page
  1. The prefix decides
  2. Which keys may be public
  3. Search what you ship, not what you wrote
  4. If you find one

"It's in .env, so it's safe" is the misunderstanding behind most of these leaks. A .env file keeps a value out of your git repository. Whether it stays out of the browser depends on the variable's name.

The prefix decides

Build tools copy specially named variables into client code as plain strings:

FrameworkPrefix that ships to the browser
Next.jsNEXT_PUBLIC_
Vite (React, Vue, Svelte)VITE_
Create React AppREACT_APP_
SvelteKit, AstroPUBLIC_
Expo / React NativeEXPO_PUBLIC_
NuxtNUXT_PUBLIC_

So NEXT_PUBLIC_OPENAI_API_KEY is a published key. The usual way it gets there: code calls an API from a client component, the variable is undefined in the browser, and the suggested fix (from a forum or an assistant) is "add the NEXT_PUBLIC_ prefix". The error goes away. The key goes public.

Mobile apps are the same. A key inside an app binary can be extracted.

Which keys may be public

Fine in the browser, by design:

  • Supabase publishable key (sb_publishable_...) or the legacy anon key. Safe only when RLS is set up correctly.
  • Stripe publishable key (pk_live_..., pk_test_...).
  • Firebase web config (apiKey, projectId, and the rest).
  • Analytics and maps IDs, ideally restricted by domain.

Never in the browser:

  • Supabase secret key (sb_secret_...) or the legacy service_role key. It bypasses RLS completely.
  • Stripe secret and restricted keys (sk_live_..., rk_live_...), webhook signing secrets (whsec_...).
  • LLM provider keys: OpenAI, Anthropic, Google, and so on. A leaked key is someone else's free usage on your invoice.
  • Database connection strings, JWT signing secrets, email and SMS provider keys, cloud credentials.

A note on Supabase naming: its documentation says the legacy anon and service_role keys are being deprecated by the end of 2026 in favour of publishable and secret keys. Older tutorials and AI-generated code still use the old names. The rule did not change: one is for browsers, the other only for servers.

Search what you ship, not what you wrote

Source code can look clean while the build contains the key. Build, then search the output:

bash
npm run build

grep -rnoE "sk_live_[A-Za-z0-9]+|sk-[A-Za-z0-9_-]{20,}|sb_secret_[A-Za-z0-9_-]+|service_role|whsec_[A-Za-z0-9]+|AKIA[0-9A-Z]{16}" \
  .next/static dist build 2>/dev/null | cut -c1-160

Legacy Supabase keys are JWTs and do not contain the words service_role in readable form, so also search for long strings starting with eyJ and decode any you find locally (do not paste keys into online decoders):

bash
echo '<middle-part-of-the-jwt>' | base64 -d 2>/dev/null

If the decoded payload says "role":"service_role", that is the admin key.

You can run the same check on the live site: open DevTools, go to Sources, and search across all files (Ctrl+Shift+F) for the patterns above.

Also list what your code asks to expose:

bash
grep -rnE "(NEXT_PUBLIC|VITE|REACT_APP|EXPO_PUBLIC|NUXT_PUBLIC|PUBLIC)_[A-Z0-9_]*(SECRET|SERVICE|PRIVATE|TOKEN|API_KEY)" \
  --include=*.ts --include=*.tsx --include=*.js --include=*.jsx --include=.env* . 2>/dev/null | grep -v node_modules

Every hit deserves a look. Some are fine (a public Maps key). Many are not.

If you find one

1. Rotate it now. Create a new key at the provider and revoke the old one. Removing it from the code and redeploying is not enough: the old bundles are cached, archived and possibly already scraped. Assume the key was copied.

2. Check for use. Look at the provider's usage and logs for the period the key was exposed. For a database key, check for unexpected reads, new admin users and changed rows.

3. Move the call to the server. The browser calls your endpoint, your endpoint calls the provider:

TypeScript
// app/api/summarise/route.ts
import OpenAI from 'openai';
import { auth } from '@/lib/auth';

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // no NEXT_PUBLIC_

export async function POST(req: Request) {
  const session = await auth();
  if (!session) return Response.json({ error: 'Unauthorized' }, { status: 401 });

  const { text } = await req.json();
  const completion = await openai.chat.completions.create({
    model: 'gpt-4o-mini',
    messages: [{ role: 'user', content: `Summarise:\n\n${String(text).slice(0, 8000)}` }],
    max_tokens: 400,
  });
  return Response.json({ summary: completion.choices[0].message.content });
}

The endpoint needs its own auth and limits, or you have rebuilt the leak with an extra step. See our post on capping LLM API spend.

4. Add a guard. In Next.js, import 'server-only' at the top of any module that reads secrets makes the build fail if a client component imports it.

Keys in the bundle are check 3 in our security checklist for vibe-coded apps. Keys in git history are a separate problem with a similar fix: see keys committed to GitHub. If you would like someone to scan your build, rotate what leaked and move the calls server-side, that is part of our app rescue and security audit.

All articles →

Ready to discuss your project with us?

idea
*
*
*
I'm interested in...
Web Development
App Development
UX/UI Design
DevOps
Artificial Intelligence And Machine Learning
QA Testing
Mobile Development
Consultation
OutSource
Project budget (USD)
≤ $5K
$10K-$20K
$30K-$40K
$50K-$60K
>$100K
Upload file