Browser voice sessions with short-lived client credentials
Run an optional browser voice session with scoped short-lived credentials and handle microphone state, interrupted turns and disconnects.
By Invicly Tech, , in n8n, AI Automation and Voice Agents. About 9 minutes to read.
In short
A browser voice session lets a visitor talk to the assistant from a web page, with no phone call. Your server never hands the browser its real API key. It mints a short-lived client credential and the browser uses that to open a WebRTC connection, which carries the audio.
Think of it like this: It is like a hotel front desk giving you a room key card that opens one door for one night, instead of handing you the master key.
Explained simply
A browser voice session means a visitor clicks a button on your web page and talks to the assistant through their microphone. Nothing is dialled. The audio travels over the internet between the browser and the voice provider, using a browser feature called WebRTC.
The tricky part is the key. To use the provider, something must prove it is allowed. If you put your real API key in the page, anyone can copy it from the browser tools and run up your bill. So your own server holds the real key and hands the browser a temporary credential instead.
That temporary credential is short-lived and limited to one session. Your server decides who gets one. It can check that the visitor is signed in, count how many they have asked for and refuse when it is too many.
On the page, the browser asks permission to use the microphone. Some visitors say no, and some browsers block it. Plan for that: show a friendly message and offer to type instead. Also plan for a network that drops mid-sentence.
Press Play on a diagram to walk through it one step at a time.
- Browser to Your server: Ask for a session token1Ask for a session token
- 2Check the visitor, apply limitsYour server to Your server: Check the visitor, apply limits
- Your server to Voice provider: Create client secret with the real key3Create client secret with the real key
- Voice provider to Your server: Short-lived secret and expiry4Short-lived secret and expiry
- Your server to Browser: Return only the short-lived secret5Return only the short-lived secret
- Browser to Voice provider: WebRTC offer with that secret6WebRTC offer with that secret
- Voice provider to Browser: Answer, then audio flows both ways7Answer, then audio flows both ways
- Permission
- Microphone denied
- No microphone found
- Page not on HTTPS
- Credential
- Expired secret
- Server refused to mint
- Rate limit hit
- Network
- Connection drops
- High jitter
- Firewall blocks WebRTC
- Turn
- Visitor interrupts
- Long silence
In depth
Why the browser gets a different credential
Anything sent to a browser can be read by the person using it. A standard API key can do everything your account can do, for as long as it lives. A client secret is made for exactly this case. Your server creates it by calling the provider with the real key, and it comes back with an expiry time. The browser uses it once to start a session and never sees the real key. Check the provider's current docs for the exact endpoint, the model name to request and how long the secret lasts, because these change.
- Create the secret per session, on demand
- Check sign-in and rate limit before minting
- Never log the secret
- Return only the secret and its expiry to the browser
How the connection is set up
The browser creates a peer connection, adds the microphone track, and opens a data channel for JSON events. It makes an offer, which is a text description of what it can send and receive, and posts it to the provider using the client secret. The provider replies with an answer. After the browser applies the answer, audio flows both ways and events arrive on the data channel. Your server is no longer in the audio path, which keeps latency low and your server load small.
- 1Add mic track, open data channelBrowser to Browser: Add mic track, open data channel
- 2Create offer (SDP)Browser to Browser: Create offer (SDP)
- Browser to Voice provider: Post offer with client secret3Post offer with client secret
- Voice provider to Browser: Return answer (SDP)4Return answer (SDP)
- Voice provider to Browser: Audio and events flow5Audio and events flow
Interruptions and disconnects
When a caller talks over the assistant, the page should stop playing the assistant's audio right away. Otherwise the user hears the old answer while speaking a new question. The provider sends events that tell you the caller started speaking, and you should respond to them. For disconnects, listen to the connection state. If it fails, stop the microphone, tell the visitor in words, and offer a retry that fetches a fresh credential. Do not reuse an expired one.
- Stop playback when the caller starts speaking
- Show a visible microphone indicator
- Release microphone tracks when the call ends
- Offer text if audio keeps failing
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Mint short-lived client credentials on the server~40m
- 2Request microphone access~40m
- 3Stream audio over WebRTC~40m
- 4Handle interrupted turns~40m
- 5Recover from disconnects~40m
Key points
- The real API key stays on the server. The browser only ever sees a short-lived, scoped credential.
- The browser asks for microphone permission with getUserMedia. The visitor can say no, so design for that.
- WebRTC carries audio in both directions, plus a data channel for small JSON events such as a transcript or a stop signal.
- When the visitor interrupts, stop playing the assistant audio at once and let the new turn begin.
- Connections drop on weak networks. Detect it, say so, and offer to reconnect or switch to text.
Key terms
Tap a card to flip it. 0/5 known
Examples
app.get("/token", async (req, res) => {
if (!req.session.userId) return res.sendStatus(401);
const r = await fetch("https://api.openai.com/v1/realtime/client_secrets", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ session: { type: "realtime", model: MODEL } }),
});
const data = await r.json();
res.json({ value: data.value, expires_at: data.expires_at });
});Server route that mints a credential. Check the provider docs for the current endpoint and model name.
Ask for the microphone and handle a refusal
Prerequisites: a page served over HTTPS or on localhost. Steps: call getUserMedia, catch the error, then show a text fallback. Expected evidence: the browser shows a permission prompt, and if you click Block, your page shows the fallback instead of a blank screen. Cleanup: stop the tracks when you finish.
async function startMic() {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
return stream;
} catch (err) {
showMessage("We could not use your microphone. You can type instead.");
showTextBox();
return null;
}
}
function stopMic(stream: MediaStream) {
stream.getTracks().forEach((t) => t.stop());
}A safe token route for the appointment desk
Scenario: Contoso Clinic shows a voice button to signed-in patients only. The server checks the session, allows five tokens per hour per patient, mints a secret and returns only the secret. If any check fails, it returns an error and the button shows the text form. Use a test key and a fake patient while learning.
app.get("/token", async (req, res) => {
const id = req.session.patientId;
if (!id) return res.sendStatus(401);
if (!(await underLimit(id, 5, 3600))) return res.sendStatus(429);
const secret = await mintClientSecret(); // calls the provider
res.json({ value: secret.value, expires_at: secret.expires_at });
});Quick reference
- Real API key: server only. Browser gets a client secret.
- Mint per session, after a sign-in check and a rate limit.
- getUserMedia needs HTTPS (or localhost) and user permission.
- Open the data channel before creating the WebRTC offer.
- Stop assistant playback the moment the caller starts speaking.
- On disconnect: stop mic tracks, tell the user, mint a fresh secret to retry.
Common mistakes
- Putting the standard API key in front-end code or an environment variable that the bundler exposes.
- Minting credentials for anyone who asks, with no sign-in check or rate limit.
- Forgetting to stop the microphone tracks when the session ends, so the browser keeps showing the recording indicator.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a function that requests the microphone and shows a text box if the visitor says no.
- Exercise 2medium
Add a per-user limit of three tokens per ten minutes to a token route. Return 429 when exceeded.
- Exercise 3hard
Design the reconnect flow for a dropped connection, in steps, including cleanup and what the visitor sees.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is it safe to put my API key in front-end code if the site is small?
- No. Keys in browser code are easy to copy. Use a server route that mints short-lived credentials.
- Why does the microphone not work on my page?
- Browsers allow it only on HTTPS or localhost, and only after the user grants permission.
- Do I need WebRTC for every voice agent?
- No. It suits browser sessions. Phone calls use SIP, and a server-to-server agent can use a WebSocket.