Engineering

How to keep your AI API keys safe when you build a chatbot

By Isuru Wickramasinghe Jun 2, 2026 7 min read

If you take one thing from everything I've written about chatbots, make it this: your AI provider's API key must never touch the browser. I've seen keys leaked in page source more times than I'd like, and the cleanup is never fun — someone racks up your bill overnight, or worse.

Why it's so easy to get wrong

The naive way to build a chatbot is to call the AI provider straight from JavaScript on the page. It works instantly in a demo, so people ship it. The problem is that anything in front-end code is readable by anyone — right-click, view source, and there's your key. Bots crawl the web looking for exactly this.

The fix: a thin server in the middle

The pattern is boring and bulletproof. You put a small server function between your page and the AI provider. The browser sends the user's message to your function; your function adds the secret key and forwards the request to the provider; the answer streams back through your function to the page. The key lives on the server, as an environment variable, and never leaves it.

Browser  →  your /api/chat  →  AI provider
              (holds the key)

On a platform like Vercel this "server" is a single small file, and the key is set in the project settings, not in your code. Your repository never contains the secret at all.

While you're at it, add these guards

Hiding the key is step one. A production endpoint should also:

  • Lock the allowed origins so only your domain can call it. Otherwise someone can point their own site at your endpoint and spend your budget.
  • Cap the message length and history size. This bounds both cost and abuse. There's more on that in the cost breakdown.
  • Keep the system prompt server-side. If the persona and any private business context live in the function rather than the page, visitors can't read or rewrite them. This matters more than people realise.
  • Add basic rate limiting if you expect traffic — a simple per-IP cap stops the worst of it.

If a key does leak

Rotate it immediately — revoke the old one and issue a new one in your provider's dashboard. Don't try to "hide" a leaked key; treat it as burned. Then move it server-side so it can't happen again.

None of this is advanced. It's a small function and four sensible defaults. But it's the difference between a chatbot you can leave running and one that becomes a liability. Build it right once and you never think about it again.

Ad

Isuru Wickramasinghe

Isuru Wickramasinghe is the founder and lead developer at Amcon Ceylon, a digital product studio in Colombo. He builds and ships small web products, and has delivered 700+ freelance projects across Upwork, Fiverr and Freelancer.

Want this on your site?

Vozzo drops an AI assistant into any website in one line — streaming, branded, and safe.

See how it works