Your OpenAI API key is in the frontend: what to do right now

Updated

If the key is in your JavaScript bundle, anyone can copy it and spend your balance. Revoke it and create a new one first, then check usage for calls you didn’t make, set a spending limit, and move every AI call into a server function that checks the user and limits requests. Also scan the git history: removing the key from the latest commit doesn’t remove it from older ones.

Check if it’s exposed

Open the live site, DevTools → Sources, and search all files for sk-. Also search the repository for OPENAI_API_KEY and look at how it is read: VITE_ or NEXT_PUBLIC_ in the name means it is shipped to the browser.

Do this in order

  1. Revoke the key in the OpenAI dashboard and create a new one. Do it before anything else: a copied key keeps working until it’s revoked.
  2. Look at usage for the last days. Spikes at odd hours or models you don’t use mean someone else used it.
  3. Set a monthly budget for the project, so the next leak has a ceiling.
  4. Put the new key only in server-side secrets: Edge Function secrets, Vercel environment variables without a public prefix, Replit Secrets.
  5. Scan the whole git history with a tool such as gitleaks. If the repository was ever public, treat every key in its history as leaked.

Move the call to a server function

A minimal Supabase Edge Function that only answers signed-in users:

import { createClient } from 'npm:@supabase/supabase-js@2'

Deno.serve(async (req) => {
  const supabase = createClient(
    Deno.env.get('SUPABASE_URL')!,
    Deno.env.get('SUPABASE_ANON_KEY')!,
    { global: { headers: { Authorization: req.headers.get('Authorization') ?? '' } } }
  )
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) return new Response('Unauthorized', { status: 401 })

  const { prompt } = await req.json()
  const res = 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: 'gpt-5-mini', input: String(prompt).slice(0, 4000) })
  })
  return new Response(res.body, { status: res.status })
})

Add a per-user limit on top, for example a counter table checked before the call. Without it, one signed-in user can still burn the budget overnight.

Sources