VibecodingSecurity essentialsLevel 2: Context

How Do You Keep API Keys Out of the Browser?

Any key your page's JavaScript can use, every visitor can read. Keep real secrets on a server or in a server function, and have the browser call that function instead. A few keys are public by design, so the job is knowing which keys are which, then testing your live site to prove it.

Prompt to copy
Audit this project for secrets that can reach the browser, then fix them. Never print a secret's value in your replies.

1. List every environment variable and hard-coded credential: name, file, and whether the code using it runs in the browser. Treat NEXT_PUBLIC_, VITE_, PUBLIC_ and NUXT_PUBLIC_ variables as browser-visible.
2. Sort them into public by design (Supabase publishable, Stripe pk_, Firebase API key) and secret (everything else).
3. Move each secret call into a server-side function. The browser may only call my own function. Use this shape for [Next.js / Supabase Edge Functions]:

// Next.js: app/api/ai/route.ts
import { createClient } from "@/lib/supabase/server"; // my project's server client

export async function POST(request: Request) {
  const supabase = await createClient();
  const { data } = await supabase.auth.getClaims();
  if (!data?.claims) return Response.json({ error: "Sign in first" }, { status: 401 });

  const { prompt } = await request.json();
  if (typeof prompt !== "string" || prompt.length > 4000) {
    return Response.json({ error: "Invalid input" }, { status: 400 });
  }

  const upstream = await fetch("[AI_PROVIDER_URL]", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.AI_API_KEY}`,
    },
    // Match this body to my provider's docs.
    body: JSON.stringify({ model: "[MODEL]", messages: [{ role: "user", content: prompt }] }),
  });
  return new Response(upstream.body, { status: upstream.status });
}

// Supabase Edge Function: supabase/functions/ai/index.ts
import { withSupabase } from 'npm:@supabase/server@1'

export default {
  fetch: withSupabase({ auth: 'user' }, async (req, ctx) => {
    const { prompt } = await req.json()
    if (typeof prompt !== 'string' || prompt.length > 4000) {
      return Response.json({ error: 'Invalid input' }, { status: 400 })
    }
    const upstream = await fetch('[AI_PROVIDER_URL]', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${Deno.env.get('AI_API_KEY')}`,
      },
      body: JSON.stringify({ model: '[MODEL]', messages: [{ role: 'user', content: prompt }] }),
    })
    return new Response(upstream.body, { status: upstream.status })
  }),
}

4. Add a per-user limit of [20] calls per [hour] to each route that spends money, and return 429 past it.
5. Remove the old browser-visible variable from .env files and from my host's settings. Confirm .env files are in .gitignore.
6. Finish with: the keys I must rotate because they were exposed, where each new secret must be set, and the exact test that proves the browser no longer sees it.
Public by designyour access rules protect the data
  • Supabase publishable keys (sb_publishable_)
  • Stripe publishable keys (pk_)
  • Firebase API keys
Server onlynever in browser code
  • Supabase secret keys (sb_secret_)
  • Stripe sk_ and rk_ keys
  • Gemini Developer API keys
  • Any AI, email or SMS credential
From Supabase, Stripe and Firebase docs, checked November 6, 2026. The last server-only line is a rule of thumb, not a vendor figure.
  • 400+exposed secrets foundPassive scans of public vibe-coded apps
  • 5,600+public apps scannedHeavily skewed to Lovable, by Escape's own account
Source: Escape, October 2025. Escape sells security testing, calls these counts a lower bound, and its report page gives a different app count, so don't read this as a per-app rate.

Try it now

  1. 1Open your live site in Chrome and press F12. In the Network panel, tick Preserve log, then use the feature that calls the paid service. If a request goes straight to the provider's domain instead of your own, the key is in the browser.
  2. 2Press Ctrl+Shift+F (Command+Option+F on Mac) to open the Search panel, which searches all loaded resources. Search one at a time for sk_live, sk-, sb_secret, service_role, api_key and secret.
  3. 3In your repository, check history too: git log --all -p -S "sk_live". Repeat with any other prefix your services use.
  4. 4It worked when the only keys you find are the public-by-design ones, and the paid feature's request goes to your own domain. A Bearer value in a request can be the signed-in user's own token, which is normal.

Use it when

Any time the app calls a paid or private service: an AI model, email, SMS, payments, a database admin connection or file storage. Run the test after the AI adds any integration, and again before you share a public link.

Skip it when

Don't build a proxy for keys that are public by design. Routing a Stripe pk_ key or a Supabase publishable key through your own server adds code and no safety. Spend that time on your access rules instead.

Why it works

Frameworks copy certain variables into the JavaScript they send to visitors. Next.js does this at build time for anything starting with NEXT_PUBLIC_, and Vite does it for VITE_. Vite's docs say those variables should not hold API keys. Variables without the prefix stay on the server, so the prefix decides who can read the value.

Vendors draw the line like this:

  • Public by design: Supabase publishable keys (sb_publishable_, formerly anon), Stripe publishable keys (pk_) and Firebase API keys. Your access rules protect the data, not the key.
  • Server only: Supabase secret keys (sb_secret_, formerly service_role), which Supabase says bypass every row level security policy. Stripe sk_ and rk_ keys. Gemini Developer API keys, which Firebase's docs call out as an exception that must never sit in your code.
  • Rule of thumb, not a vendor figure: treat any AI, email, SMS or database password credential as server only, because each one spends your money or reads your data.

Example

A recipe app calls an AI provider from a React component using VITE_AI_KEY. In the Network panel, the request goes to the provider's domain with the key in its Authorization header, so any visitor can copy it.

The fix uses a Supabase Edge Function. Run supabase secrets set AI_API_KEY=[NEW_KEY], which Supabase says takes effect without a redeploy, and paste the function from the prompt above. Delete VITE_AI_KEY everywhere and create a new key at the provider, because older builds and old commits still contain the first one. Repeat the test. The browser should now call only your function, and calling it with no login should return 401.

Going further

Rotate first and clean up second. GitHub's guide says to revoke or rotate a leaked secret first, and that this may be enough, since rewriting history with git-filter-repo --sensitive-data-removal has real side effects such as changed commit hashes and lost pull request diffs.

A few details are easy to miss. Stripe keeps old and new keys working for up to 7 days when you rotate, and picking Now under Expiration kills the old key immediately, which is what you want after a leak. Stripe recommends restricted rk_ keys over sk_ keys for most uses. Supabase suggests one secret key per backend component, so one leak means one rotation. On Vercel, choose the Secret type so values are write-only after saving.

GitHub's push protection for users is on by default for pushes to public repositories, and secret scanning runs free on public ones. Private user-owned repositories generally don't get either scan, so a private repo isn't a safe place for keys.

Common mistakes

  • Accepting an AI fix that renames a key to NEXT_PUBLIC_ or VITE_ because the variable was undefined in the browser. The error goes away because the secret is now public.
  • Building a proxy with no login check or limit. Anyone can call your route and spend your key. OWASP's API guidance also says to set spending limits with every paid provider, or billing alerts if limits aren't offered.
  • Deleting the key from the code without rotating it. Old commits and old deployments still contain it.
  • Treating Supabase's browser check as protection. It returns 401 for a secret key used from a browser, but Supabase says this isn't a security boundary, since other tools can still use a leaked key.

Sources

Checked 6 November 2026. Products change often, so confirm details with the vendor.

Related

Beyond the course