Skip to content
mentoor

Topic 1 of 4 · 4 min read

Keeping provider keys on the server

Goal: Move a provider call out of client code into a server route that authenticates the user before calling the model.

A provider key belongs on your server only: the browser or phone app calls your route, and your route checks who the user is before it calls the model. Anything shipped to a client can be read by the person who owns the client.

Check yourself · 1 of 3

A web app calls the model provider straight from the browser using a key stored in a build-time variable. What is the core problem?

Choose one answer

Why it matters

An API key is a password that spends your money. If it sits in a JavaScript bundle, a mobile app or a public repository, anyone can copy it from the network tab, unpack the app, or find it with a search. They then call Claude, GPT or Gemini as you, and your bill pays for it. Providers say this plainly: do not deploy keys in client-side code. Obfuscating the key or hiding it in an environment variable that the bundler inlines does not help, because the value still ends up in the file the user downloads.

How to do it

  1. Create a server route such as POST /api/chat. It is the only code that holds the provider key, read from the server environment or a secret manager.
  2. Authenticate first. Check the session or token, load the user, and reject the call before any provider request is made.
  3. Validate the input. Accept only the fields you expect (message text, a conversation id). Set the model, system prompt and max_tokens on the server. Never let the client choose them.
  4. Call the provider, then return only what the client needs. Do not forward raw provider errors or headers; they can leak account details.
  5. For realtime features (voice, streaming over WebRTC), the browser cannot proxy every audio frame through a slow route. Instead the server calls the provider to mint a short-lived client secret for that one session, and the browser uses it. If it leaks, it expires in minutes.

Before and after

Before, the key travels in the bundle:

// chat.ts (runs in the browser)
const res = await fetch("https://api.openai.com/v1/chat/completions", {
  headers: { Authorization: "Bearer sk-live-REDACTED" },
  body: JSON.stringify({ model: "gpt-5", messages }),
});

After, the browser calls your route and the server owns the key:

// server route
export async function POST(req: Request) {
  const user = await requireUser(req);
  const { message } = await parseBody(req);
  const out = await provider.chat({
    model: "gpt-5",
    max_tokens: 800,
    messages: [{ role: "user", content: message }],
  });
  return Response.json({ text: out.text });
}

What goes wrong

  • A proxy with no login. You hid the key but left the route open, so anyone on the internet can use it as a free model. Authentication is half the job.
  • The client picks the model. A request body with "model": "the-most-expensive-one" is accepted as is.
  • Keys in the mobile app "because it is compiled". Apps are unpacked in minutes.
  • Leaking through logs and errors. Logging the full request headers writes the key into a log file others can read.

Examples

The key found in a bundle

A startup ships a React app that calls the provider directly with NEXT_PUBLIC_LLM_KEY. The NEXT_PUBLIC_ prefix tells the build tool to copy the value into the browser bundle. A search of the deployed .js file for sk- finds it in seconds. The fix is a rename to a server-only variable, a new route that reads it, and a rotation of the exposed key, because the old one must be treated as stolen.

Voice in the browser

A voice assistant needs the browser to stream audio to the model. The server route POST /api/voice-session checks the logged-in user, asks the provider for a client secret that lasts a few minutes, and returns only that secret. The browser connects with it. The main key never leaves the server, and a copied client secret is useless soon after.

Key points

  • Provider keys live only on the server; clients call your own route, never the provider directly.
  • Authenticate and authorise the user before the route makes any provider call; a hidden key behind an open route is still a free model for everyone.
  • Set the model, system prompt and token limit on the server and ignore any such fields sent by the client.
  • Bundler-inlined environment variables, obfuscation and compiled apps do not hide a key from the person who has the file.
  • For realtime clients, mint a short-lived client secret on the server for each session instead of shipping the long-lived key.

Common mistakes

  • Moving the key into an environment variable that the bundler inlines into client code.
  • Protecting the key but leaving the proxy route open to anonymous callers.
  • Letting the request body choose the model, system prompt or max tokens.
  • Returning raw provider error objects to the client, which can expose account details.

Check yourself · 2 of 3

You move the provider call into a server route and keep the key in the server environment. Which step is still missing?

Choose one answer

Check yourself · 3 of 3

A browser voice feature must stream audio to the provider in real time. What is the recommended way to authorise it?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic