Quick Start (WebRTC)
Palabra API client
Consider using Palabra API JavaScript client for WebRTC-based integrations.
How it works
- You create a session and receive a WebRTC API URL and a session token.
- You connect to WebRTC API URL and publish your original audio track.
- You wait for
palabra_translator_*, sendset_taskwith your language settings over the reliable data channel, and retry untiltask_statusconfirms that the task is running. - Palabra transcribes, translates, and synthesizes your speech in real time and publishes the translated audio track to the same room. You are auto-subscribed to it and can play it back instantly.
Step 1. Get API Credentials
Create an API Key on the Palabra API Keys page. See API Keys for details.
Step 2. Create a Session
Create a session on your backend with POST /session-storage/v2/sessions, using your API Key and {"intent": "s2s", "connection_type": "webrtc"}. See Session Management.
Never include the account API Key in browser or mobile code. For a user's device, apply the limits described in Temporary Sessions, then send only the session credentials and connection details to the client.
Request Example
Run either request on your backend:
const { data: response } = await axios.post(
"https://api.palabra.ai/session-storage/v2/sessions",
{
intent: "s2s",
connection_type: "webrtc",
},
{
headers: {
Authorization: "Bearer <API_KEY>",
},
}
);
const session = response.data;
curl -X POST https://api.palabra.ai/session-storage/v2/sessions \
-H "Authorization: Bearer <API_KEY>" \
-H "Content-Type: application/json" \
-d '{
"intent": "s2s",
"connection_type": "webrtc"
}'
Response Example
{
"ok": true,
"data": {
"id": "ses_k3v9x2m7q4t8w1z5b6n0c2d4",
"token": "<session-token>",
"intent": "s2s",
"connection_type": "webrtc",
"status": "pending",
"connect_by": "2026-10-05T11:00:00Z",
"webrtc": {
"url": "https://api.palabra.ai/livekit/",
"room_name": "6bbcf900"
}
}
}
Use data.token and data.webrtc.url from the response body on your client. Treat the token as an opaque string; do not decode it or assume it is a JWT. data.id identifies the session for cleanup. The session must open its stream before connect_by.
Step 3. Connect to the Translation Room
Use the LiveKit SDK to join session.webrtc.url with session.token, where session is the session object supplied by your backend.
livekit-client 2.22.4 with LiveKit server 1.13.10 (Chrome). Confirm the supported version for your webrtc.url with Palabra support before using this installation command. Newer versions, including server 1.13.11, need a compatibility check; the reference test does not cover Safari, Firefox, or native mobile SDKs.Upgrade the server before its clients. Clients 2.18 and newer were unstable with server 1.8.4 when falling back from /rtc/v1 to /rtc. JS and native mobile SDKs have separate version numbers; do not use the JS version as an Android or iOS version recommendation.npm install livekit-client@2.22.4
import { Room } from "livekit-client";
const connectTranslationRoom = async (WEBRTC_URL, SESSION_TOKEN) => {
try {
const room = new Room();
await room.connect(WEBRTC_URL, SESSION_TOKEN, { autoSubscribe: true });
return room;
} catch (e) {
console.error(e);
throw e;
}
};
// The client receives session from your backend, without the account API Key.
const room = await connectTranslationRoom(session.webrtc.url, session.token);
Step 4. Publish the Original Audio Stream
Get the audio stream from your microphone and publish it to the room.
dtx and red when publishing your audio track — see Recommended settings.import { LocalAudioTrack } from "livekit-client";
const publishAudioTrack = async (room) => {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: 1 } });
const localTrack = new LocalAudioTrack(stream.getAudioTracks()[0]);
await room.localParticipant.publishTrack(localTrack, {
dtx: false,
red: false,
audioPreset: {
maxBitrate: 32000,
priority: "high"
}
});
} catch (e) {
console.error("Error while publishing audio track:", e);
throw e;
}
}
Step 5. Handle the Translated Audio Track
As soon as Palabra publishes the translated audio track to the room, you are auto-subscribed to it. Handle it in a callback and play it through the speakers.
import { RoomEvent } from "livekit-client";
const playTranslationInBrowser = (track) => {
if (track.kind === "audio") {
const mediaStream = new MediaStream([track.mediaStreamTrack]);
const audioElement = document.getElementById(
"remote-audio"
); // Your HTML audio element
if (audioElement) {
audioElement.srcObject = mediaStream;
audioElement.play();
} else {
console.error("Audio element not found!");
}
}
};
// Add a handler for the TrackSubscribed event
room.on(RoomEvent.TrackSubscribed, playTranslationInBrowser);
Step 6. Start the Translation
Send a set_task message with your translation settings through the default (empty-topic), reliable WebRTC data channel.
Wait for a participant whose identity starts with palabra_translator_. Check both the current participant list and subsequent ParticipantConnected events. Another remote participant is not the translator.
The translator may appear before its data channel or command handler is ready. ParticipantConnected and a successful publishData call do not confirm that the command was applied. Register the response handler before sending, then repeat the same set_task until you receive task_status with data.command: "set_task" and data.task_status: "running".
This helper sends immediately once the translator appears, retries after 1.25 seconds, then increases the interval by 1.5× up to 5 seconds. A 30-second overall timeout includes waiting for the translator and its acknowledgement. These are example client-side limits, not server readiness guarantees. Stop on a server error, cancellation, or disconnection.
import { RoomEvent } from "livekit-client";
const START_TIMEOUT_MS = 30000;
const INITIAL_RETRY_MS = 1250;
const MAX_RETRY_MS = 5000;
const isTranslator = (participant) =>
participant?.identity?.startsWith("palabra_translator_");
const startTranslation = (room, translationSettings, { signal } = {}) =>
new Promise((resolve, reject) => {
const message = new TextEncoder().encode(JSON.stringify({
message_type: "set_task",
data: translationSettings
}));
let settled = false;
let hasSent = false;
let retryTimer;
let timeoutTimer;
let retryDelay = INITIAL_RETRY_MS;
const finish = (error, status) => {
if (settled) return;
settled = true;
clearTimeout(retryTimer);
clearTimeout(timeoutTimer);
room.off(RoomEvent.ParticipantConnected, onParticipantConnected);
room.off(RoomEvent.DataReceived, onData);
room.off(RoomEvent.Disconnected, onDisconnected);
signal?.removeEventListener("abort", onAbort);
if (error) reject(error);
else resolve(status);
};
const onAbort = () => finish(new DOMException("Translation start cancelled", "AbortError"));
const onDisconnected = () => finish(new Error("Room disconnected before task confirmation"));
const onData = (payload, participant, _kind, topic) => {
if (!hasSent || !isTranslator(participant) || topic) return;
let response;
try {
response = JSON.parse(new TextDecoder().decode(payload));
} catch {
return; // Other room data may not be JSON.
}
if (response?.message_type === "error") {
finish(new Error(JSON.stringify(response.data)));
} else if (
response?.message_type === "task_status" &&
response.data?.command === "set_task" &&
response.data?.task_status === "running"
) {
finish(null, response);
}
};
const publish = async () => {
if (settled) return;
// Recheck presence on each retry in case the translator has left.
if ([...room.remoteParticipants.values()].some(isTranslator)) {
hasSent = true;
try {
await room.localParticipant.publishData(message, { reliable: true });
} catch (error) {
// A transport send failure can be transient; the overall timeout still applies.
console.warn("set_task send failed; retrying until the startup deadline", error);
}
}
if (!settled) {
retryTimer = setTimeout(publish, retryDelay);
retryDelay = Math.min(retryDelay * 1.5, MAX_RETRY_MS);
}
};
const onParticipantConnected = (participant) => {
if (!hasSent && isTranslator(participant)) void publish();
};
room.on(RoomEvent.DataReceived, onData);
room.on(RoomEvent.ParticipantConnected, onParticipantConnected);
room.on(RoomEvent.Disconnected, onDisconnected);
signal?.addEventListener("abort", onAbort, { once: true });
if (signal?.aborted) {
onAbort();
return;
}
timeoutTimer = setTimeout(
() => finish(new Error("Translation startup timed out before task confirmation")),
START_TIMEOUT_MS
);
// Handlers are installed before checking participants or sending the first command.
const translator = [...room.remoteParticipants.values()].find(isTranslator);
if (translator) onParticipantConnected(translator);
});
Call the helper with your complete translation settings. Handle a rejection as a failed start and release the session if you will not retry. Pass an AbortSignal so your stop button or component cleanup can cancel a pending start:
const startupController = new AbortController();
// On stop/unmount, call startupController.abort() before ending the task or disconnecting.
try {
await startTranslation(room, translationSettings, { signal: startupController.signal });
console.info("Translation task is running");
} catch (error) {
console.error("Translation did not start", error);
// Release microphone tracks and delete the unused session in your app's cleanup.
}
Use one pending set_task operation per room. Wait for it to finish before changing settings or sending another control command. Do not start another retry loop while this one is active; abort it before stopping the task. Command acknowledgements do not contain a request ID that could distinguish concurrent set_task calls.
A confirmation can have data.event: "started", "updated", "unchanged", or "resumed"; all confirm that the task is running. If an earlier acknowledgement was lost, repeating the same complete settings can return unchanged instead of started. See Translation management API for response details and rate limits.
The helper removes its listeners and timers on every completion path. It does not disconnect the room, stop microphone tracks, or delete the session; your application's session cleanup still needs to do that.
Summary
Once task_status confirms that the pipeline is running, Palabra processes your published audio track, translates it into the target languages from your settings, and publishes a translated track to the same room. The LiveKit SDK auto-subscribes you to this track, so you can play it back through the speakers in real time.
Good to know
- Pausing and stopping the translation are covered in the Translation management API.
- Delete sessions you no longer need — for example, when translation stops or the page unmounts. A v2 token can open a stream until
connect_by; reusable and single-use tokens have different reconnect rules. See Session Management. - Due to browser security restrictions, audio cannot play until the user has interacted with the page. Don't start the pipeline automatically on page load — wait for a user action (such as pressing a "Start" button) before activating audio playback.
Need help?
If you have any questions or need assistance, contact us at api.support@palabra.ai.