Call Groq, OpenRouter & Gemini APIs in One Function
Call Groq, OpenRouter and Gemini through the same OpenAI-compatible chat format. One function, three providers — plus how to keep API keys safe.
Published 2026-10-14
TL;DR
Groq, OpenRouter and Gemini all offer OpenAI-compatible chat endpoints, so one request builder can call any of them — only the URL, model name and key change. Never put a real API key in front-end code; call providers from a server or edge function.
Key takeaways
OpenAI-compatible endpoints mean the same messages array works everywhere.
Switch providers by changing the base URL and model name.
Keep keys server-side — a key in browser code is public.
This is the piece that turns a stub agent into a real one.
Why one function is enough
Most providers now copy OpenAI’s chat format. That means the request body — a model plus a messages array — is identical across Groq, OpenRouter and Gemini’s compatibility endpoint. If you read our OpenRouter guide, this is the same idea applied to more providers.
The request builder
Keep your key safe
The example deliberately doesn’t send anything. In production, put fetch(req.url, …) inside a server or edge function and read the key from an environment variable. Shipping a key in browser code is the #1 way keys get stolen.