Topic 2 of 5 · 5 min read
Transport and session architecture for voice agents
Goal: Lay out the client, server and model session for a browser voice agent and flag any design that exposes a long-lived API key to the client.
A browser voice agent has three parts, the browser, your server and the model session, and the browser must only ever hold a short-lived token, never your API key.
Check yourself · 1 of 3
A browser voice demo connects directly to the model using the team's API key stored in a front-end constant. What is the problem?
Why it matters
Anything shipped to the browser can be read by the user. A long-lived API key in client code lets anyone run up your bill and use your account. Realtime sessions are expensive per minute, so a leaked key is costly quickly.
The parts
- Browser. Captures the microphone, plays the reply audio and shows UI. It connects to the model or to a media server.
- Your server. Authenticates the user, decides what the session may do, and mints a client token: a credential that expires in about a minute and only opens a session. Both OpenAI and Gemini document an ephemeral-token flow for this.
- Model session. The live connection that carries audio and events. Its configuration (instructions, voice, tools, turn detection) is set by your server, not by the page.
Transport choice
- WebRTC suits browsers and phones. It is built for real-time audio over unreliable networks: the browser handles echo cancellation, noise suppression, jitter buffering and packet loss.
- WebSocket suits server-to-server links, such as a phone-call gateway sending audio frames to a model. You manage buffering and playback yourself.
- Media servers and frameworks (LiveKit Agents, Pipecat) sit between users and models. They give you rooms, an agent worker per call, reconnection and a place to run chained pipelines.
Session configuration
Set the instructions, voice, tool list and turn-detection options on the server when you create the session. Do not let the client send arbitrary instructions or tool definitions: a user who controls the config controls the agent.
Before and after
// Weak: key shipped in the page
const session = await connect("wss://api.example.com/realtime", {
headers: { Authorization: "Bearer " + "sk-live-...redacted" },
});
// Better: the browser asks your server, which mints a short-lived token
const { token } = await fetch("/api/voice/session", { method: "POST" }).then(r => r.json());
const pc = new RTCPeerConnection();
// ...open the session using `token`, which expires quickly
On the server, the /api/voice/session route checks the user's login and plan, creates the session with your fixed config, and returns only the token.
What goes wrong
- A "temporary" key in the front end. It gets copied into a build and cached by browsers.
- Unlimited token minting. An open endpoint lets one user open hundreds of sessions. Rate-limit and cap duration per user.
- Client-chosen config. The page sends its own system prompt or tools, so the agent can be reconfigured.
- Using WebSocket in the browser by default. You then rebuild audio handling WebRTC already does.
Examples
Token route
app.post("/api/voice/session", requireLogin, rateLimit(5, "1m"), async (req, res) => {
const token = await mintClientToken({
instructions: SUPPORT_INSTRUCTIONS,
voice: "alloy",
tools: SUPPORT_TOOLS,
});
res.json({ token });
});
The login check and rate limit protect the endpoint, the config is fixed on the server, and the browser receives only an expiring token.
Reviewing a design
A pull request opens a WebSocket from the browser to the model and reads the key from window.CONFIG.apiKey. Flag it: the key is in the page, and the page also builds the system prompt. The fix is a server route that mints a token, with WebRTC for the audio path.
Key points
- Never put a long-lived API key in browser code; have your server mint a short-lived token after checking the user.
- WebRTC suits browsers and phones because it handles echo cancellation, jitter and packet loss; WebSocket suits server-to-server audio.
- Set instructions, voice, tools and turn detection on the server, so the page cannot reconfigure the agent.
- Media servers such as LiveKit Agents and Pipecat provide rooms, per-call agent workers and reconnection.
- Rate-limit token minting and cap session length per user, because sessions cost money by the minute.
Common mistakes
- Shipping a long-lived API key in front-end code or a mobile app bundle.
- Leaving the token-minting endpoint open, so one user can start hundreds of sessions.
- Letting the client send its own system prompt or tool definitions.
- Using raw WebSocket audio in the browser and rebuilding echo cancellation and jitter handling by hand.
Check yourself · 2 of 3
Which transport is the usual choice for a voice agent running in a web browser?
Check yourself · 3 of 3
Where should a voice agent's system prompt and tool list be set?
Practice items, not counted towards your mastery.
Start here
- Realtime API guide (OpenAI API) (opens in a new tab)DocsFree
Session types, WebRTC, WebSocket and SIP transports, events and ephemeral client tokens.
- Voice activity detection in the Realtime API (OpenAI) (opens in a new tab)DocsFree
Server VAD and semantic VAD settings: threshold, silence duration, eagerness and interruption behaviour.
- Live API (Gemini API docs) (opens in a new tab)DocsFree
Gemini's streaming audio API: sessions, voice activity settings, interruptions and tool use.
More for this topic
- WebRTC: Real-Time Communication in Browsers (W3C) (opens in a new tab)StandardFree
The browser WebRTC standard behind peer connections, audio tracks and echo cancellation constraints.
- LiveKit Agents documentation (opens in a new tab)DocsFree
Building voice agents on a WebRTC media server, in chained or speech-to-speech mode.