AI API keys and system prompts in frontend code – find them and move the call server-side

By Abheesht Tripathi · Published

Risk: VITE_OPENAI_API_KEY / NEXT_PUBLIC_OPENAI_API_KEY (or a system prompt) shipped in the JavaScript bundle

Why it is public

Vite exposes every variable that starts with VITE_ to client code, and Next.js inlines every NEXT_PUBLIC_ variable into the bundle at build time. Whatever is in them is in the JavaScript every visitor downloads. If the browser calls api.openai.com or api.anthropic.com directly, the key is also visible in the Network tab on every request. “Hidden” in a minified file is not hidden.

Consequences: someone runs their own workload on your key until you hit your spending limit, or resells it. The same applies to the system prompt: OWASP's LLM07:2025 System Prompt Leakage says to treat system prompts as not secret, and never to put credentials, internal URLs or access rules in them.

Find it

npm run build
# OpenAI keys start with sk- (project keys: sk-proj-), Anthropic keys with sk-ant-
grep -rEo "sk-(proj-|ant-)?[A-Za-z0-9_-]{20,}" dist/ build/ .next/static/ 2>/dev/null | head

# variables that end up in the client
grep -rE "(VITE|NEXT_PUBLIC)_[A-Z_]*(KEY|SECRET|TOKEN)" .env* src/ app/ 2>/dev/null

Also search the bundle for a distinctive sentence from your system prompt. If it is there, assume users can read it.

Fix: call the model from your server

The browser calls your endpoint with the user's session; the endpoint checks the user, adds the system prompt and the key, and enforces limits. A Supabase Edge Function version:

// supabase/functions/chat/index.ts
import { createClient } from 'npm:@supabase/supabase-js@2';

const SYSTEM_PROMPT = 'You are the help assistant for ...';   // stays on the server

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

  const { message } = await req.json();
  if (typeof message !== 'string' || message.length > 4000) {
    return new Response('Bad request', { status: 400 });
  }

  const r = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${Deno.env.get('OPENAI_API_KEY')}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: Deno.env.get('OPENAI_MODEL'),
      max_completion_tokens: 500,
      messages: [
        { role: 'system', content: SYSTEM_PROMPT },
        { role: 'user', content: message },
      ],
    }),
  });
  return new Response(await r.text(), {
    status: r.status,
    headers: { 'Content-Type': 'application/json' },
  });
});
supabase secrets set OPENAI_API_KEY=sk-... OPENAI_MODEL=<model-name>
supabase functions deploy chat

Add CORS headers if the browser calls it from another origin. Add a per-user limit (for example a count of today's calls in a table) so one account can't run up your bill.

Then rotate the old key

A key that was ever in a public bundle or repo is leaked, even after you remove it. Create a new key in the provider's dashboard, put it in your server secrets, and delete the old one. Set a monthly budget or usage limit on the provider account while you are there.

What the system prompt should and shouldn't hold

How to verify

Rebuild and rerun the searches: no keys, no prompt text. In the browser's Network tab, AI requests go only to your own endpoint. Call that endpoint without signing in: 401. The old key returns an authentication error from the provider.

Related guides

More in AI agent and LLM app security · all guides