Why you should never call OpenAI or Claude from the browser
It's the most common leak in AI-built apps: the app calls api.openai.com or api.anthropic.com directly from the browser, so the API key has to be in the browser too. Anyone can open DevTools, copy it, and use it on your bill.
The safe pattern
Browser → your server → AI provider. Your server holds the key, checks the request, and forwards it.
Minimal example (Cloudflare Worker)
export default {
async fetch(request, env) {
if (request.method !== "POST") return new Response("Not found", { status: 404 });
const { message } = await request.json();
const res = await fetch("https://api.anthropic.com/v1/messages", {
method: "POST",
headers: {
"x-api-key": env.ANTHROPIC_API_KEY,
"anthropic-version": "2023-06-01",
"content-type": "application/json",
},
body: JSON.stringify({
model: "YOUR_MODEL",
max_tokens: 500,
messages: [{ role: "user", content: message }],
}),
});
return new Response(res.body, { headers: { "content-type": "application/json" } });
},
};
Then protect your endpoint
- Require sign-in, or at least rate-limit by IP.
- Cap
max_tokensand message length on the server. - Set a monthly spending limit in your provider's console.