Live text in a web page
Stream from a browser with a single-use token your server makes, so the page never holds your key.
A web page must never hold your API key, and a browser cannot send headers on a WebSocket. So your server makes a single-use token for every session and hands it to the page, which puts it in the WebSocket address as token. A token is valid for 15 minutes and for one session (Tokens for web pages).
Make a token on your server
Add an endpoint to your server, behind your own login, that makes a token with your key and answers with it: for example POST /api/vatis-token.
curl -sS -H "Authorization: Bearer $VATIS_KEY" -H 'Content-Type: application/json' \
-d '{"type": "realtime"}' https://api.eu.vatis.tech/v1/tokensExpected result: the token (shortened here), valid for 15 minutes and for one session.
{"token": "vatis_tk_jAk...", "type": "realtime", "expires_at": "2026-11-12T09:29:03Z"}Open the session from the page
The page captures the microphone at the device's rate (the API converts it), sends 100 ms binary frames, and shows each final with its speaker. Browsers give the microphone only to pages served over HTTPS, or from http://localhost.
<!doctype html>
<meta charset="utf-8">
<title>Live transcription</title>
<button id="go">Start</button> <span id="state"></span>
<p id="partial" style="color: grey"></p>
<div id="lines"></div>
<script>
const API = "wss://api.eu.vatis.tech";
const TOKEN_URL = "/api/vatis-token"; // your server: answers {"token": "..."}
const RATES = [8000, 16000, 22050, 24000, 44100, 48000];
const WORKLET = `
class Pcm16 extends AudioWorkletProcessor { // float samples to 16-bit PCM, 100 ms per message
constructor() { super(); this.n = Math.round(sampleRate / 10); this.out = new Int16Array(this.n); this.k = 0; }
process([input]) {
const x = input[0];
for (let i = 0; x && i < x.length; i++) {
const s = Math.max(-1, Math.min(1, x[i]));
this.out[this.k++] = Math.round(s < 0 ? s * 32768 : s * 32767);
if (this.k === this.n) { this.port.postMessage(this.out.buffer, [this.out.buffer]); this.out = new Int16Array(this.n); this.k = 0; }
}
return true;
}
}
registerProcessor("pcm16", Pcm16);`;
let ws = null, mic = null;
const $ = (id) => document.getElementById(id);
async function start() {
const ctx = new AudioContext(); // the device's rate; the API converts it to 16 kHz
if (!RATES.includes(ctx.sampleRate)) throw new Error(`sample rate ${ctx.sampleRate} not supported`);
const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 } });
await ctx.audioWorklet.addModule(URL.createObjectURL(new Blob([WORKLET], { type: "application/javascript" })));
const node = new AudioWorkletNode(ctx, "pcm16", { channelCount: 1, channelCountMode: "explicit" });
const mute = ctx.createGain(); mute.gain.value = 0; // keeps the worklet running without playing the mic back
ctx.createMediaStreamSource(stream).connect(node); node.connect(mute); mute.connect(ctx.destination);
mic = { stop() { stream.getTracks().forEach((t) => t.stop()); ctx.close(); } };
const { token } = await (await fetch(TOKEN_URL, { method: "POST" })).json();
const query = new URLSearchParams({ model_id: "vatis_ro_v9_realtime", sample_rate: ctx.sampleRate,
diarize: "true", token });
ws = new WebSocket(`${API}/v1/speech-to-text/realtime?${query}`);
ws.onmessage = (e) => {
const m = JSON.parse(e.data);
if (m.type === "session.started") {
node.port.onmessage = (a) => { if (ws && ws.readyState === WebSocket.OPEN) ws.send(a.data); }; // binary frames
$("state").textContent = "live"; $("go").textContent = "Stop";
} else if (m.type === "partial") $("partial").textContent = m.text;
else if (m.type === "final") {
$("partial").textContent = "";
if (!m.text) return;
const p = document.createElement("p"); p.textContent = m.speaker ? `${m.speaker}: ${m.text}` : m.text;
$("lines").append(p);
} else if (m.type === "error") $("state").textContent = `${m.code}: ${m.message}`;
};
ws.onclose = (e) => {
if (mic) { mic.stop(); mic = null; }
$("state").textContent += ` (closed ${e.code})`; $("go").textContent = "Start"; ws = null;
};
}
function stop() { // the last finals and session.ended follow, then the server closes
if (mic) { mic.stop(); mic = null; }
if (ws && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: "end" }));
}
$("go").onclick = () => (ws ? Promise.resolve(stop()) : start()).catch((err) => { $("state").textContent = err.message; });
</script>Expected result: press Start and allow the microphone. The page says live, partial text shows in grey, and each final becomes a line with its speaker. Stop sends end: the last finals and session.ended follow, then the page shows (closed 1000).
unauthorizedand(closed 1008): the token was already used, or it expired. Make a new token for every session.sample rate ... not supported: the device's rate is not one the API takes (Query parameters).- No microphone: the page is not served over HTTPS.
The worklet sends Int16Array buffers as they are in memory: little-endian on every common browser platform. This page ends with its session when the server restarts or the connection drops; to go on with no gap, see Reconnect after a restart.