icy-beard-64788
12/05/2025, 4:21 PMtall-airline-16756
12/05/2025, 4:21 PMicy-beard-64788
12/05/2025, 4:21 PMtall-airline-16756
12/05/2025, 4:22 PMLiveKitRoom React component to connect and render — that component cannot start recording by itself. To record a session you must start Egress from your backend (server-side). Here are the concise options and a minimal Node.js example to get you started.
Which option you want depends on goal:
• Full-room video (recommended): Room Composite Egress — records all participants into a single MP4/HLS or streams to RTMP; supports layouts (grid, speaker) and custom HTML templates.
• Auto-record on room creation: AutoEgress — automatically records every room when created.
• Agent sessions: If you're using AI agents, enable record: true when starting the agent session.
Minimal Node.js example (start Room Composite Egress from your backend):
import { RoomServiceClient } from 'livekit-server-sdk';
const roomService = new RoomServiceClient(
'wss://your-project.livekit.cloud',
'API_KEY',
'API_SECRET',
);
await roomService.startRoomCompositeEgress('my-room', {
layout: 'grid',
audioOnly: false,
fileOutputs: [{
filepath: 'recordings/session.mp4',
s3: {
bucket: 'my-bucket',
accessKey: '...',
secret: '...',
region: 'us-east-1',
},
}],
});
Notes:
• Call this from your backend, not the browser.
• You need API key/secret with permission to start egress and configured storage (S3/GCS/Azure) or RTMP target.
• Recording will stop when the room ends or per egress lifecycle rules (unless using AutoEgress).
If you want, tell me:
• Do you want a single MP4 of the whole room, HLS + segments, or RTMP streaming?
• Are you using LiveKit Cloud or self-hosted LiveKit?
• Do you need a sample for another language (Go/CLI) or an AutoEgress example?
I can then give the exact backend sample and configuration for your case and storage target.
Sources: Composite and web recordings | LiveKit docs | Custom recording templates | LiveKit docs | Auto egress | LiveKit docs | Agents (Node.js) | livekit/livekit_composite | DeepWiki | Recording and export | LiveKit docstall-airline-16756
12/05/2025, 4:22 PMicy-beard-64788
12/05/2025, 4:23 PMtall-airline-16756
12/05/2025, 4:23 PMLiveKitRoom cannot start recordings).
Quick checklist and next steps I can provide:
1. Choose output:
◦ Single MP4 (Room Composite) — recommended to capture avatar + participants.
◦ HLS segments + playlist.
◦ RTMP stream.
◦ Audio-only (OGG/MP3) if you only need voice.
1. Ensure permissions:
◦ Use an API key/secret that has the roomRecord permission.
1. Start Egress from your backend (example languages: Node.js, Go, Python, or CLI). Minimal Node.js example to start a Room Composite MP4 to S3:
import { RoomServiceClient } from 'livekit-server-sdk';
const roomService = new RoomServiceClient('wss://your-project.livekit.cloud', 'API_KEY', 'API_SECRET');
await roomService.startRoomCompositeEgress('your-room-name', {
layout: 'grid',
audioOnly: false,
fileOutputs: [{
filepath: 'recordings/session.mp4',
s3: {
bucket: 'your-bucket',
accessKey: '...',
secret: '...',
region: 'us-east-1',
},
}],
});
1. Stop recording:
◦ Call StopEgress via API using the returned egress_id, or let the Room Composite stop when the room ends/all participants leave.
Tell me which of these you want and I’ll provide the exact backend sample and configuration:
• Preferred output (MP4 / HLS / RTMP / audio-only)
• Storage target (S3 / GCS / Azure / RTMP URL)
• Backend language (Node.js / Go / Python / CLI)
I’ll give the complete code and any extra config (IAM settings, bucket path, or AutoEgress example) once you pick options.
Sources: LiveAvatar virtual avatar integration guide | LiveKit docs | Recording and export | LiveKit docs | Composite and web recordings | LiveKit docs | Egress API | LiveKit docs | Auto egress | LiveKit docsicy-beard-64788
12/05/2025, 4:27 PMtall-airline-16756
12/05/2025, 4:27 PMaudioOnly: true if you only want audio). You need an API key/secret with roomRecord permission.
1) MP4 to S3
import { RoomServiceClient } from 'livekit-server-sdk';
const svc = new RoomServiceClient(
'wss://your-project.livekit.cloud',
'API_KEY',
'API_SECRET',
);
await svc.startRoomCompositeEgress('your-room-name', {
layout: 'grid',
audioOnly: false,
fileOutputs: [{
filepath: 'recordings/session.mp4',
s3: {
bucket: 'your-bucket',
accessKey: 'S3_ACCESS_KEY',
secret: 'S3_SECRET',
region: 'us-east-1',
},
}],
});
2) HLS (segments + playlist) to S3
await svc.startRoomCompositeEgress('your-room-name', {
layout: 'speaker',
audioOnly: false,
hls: {
segmentOutputs: [{
filenamePrefix: 'recordings/session',
s3: {
bucket: 'your-bucket',
accessKey: 'S3_ACCESS_KEY',
secret: 'S3_SECRET',
region: 'us-east-1',
},
}],
playlistName: 'session.m3u8',
},
});
3) MP4 to Azure Blob
await svc.startRoomCompositeEgress('your-room-name', {
layout: 'grid',
audioOnly: false,
fileOutputs: [{
filepath: 'recordings/session.mp4',
azure: {
container: 'your-container',
storageAccount: 'your-account',
storageKey: 'AZURE_STORAGE_KEY',
},
}],
});
Stopping a recording
• The API returns an egress_id you can use to stop via StopEgress, or Room Composite stops automatically when the room ends/all participants leave.
Notes & quick tips
• Audio is included by default when audioOnly: false. Use audio mixing options if you need separate channels or special mixing.
• Ensure the API key has roomRecord permission and your storage credentials (S3/Azure) are valid and have write access.
• If you want AutoEgress (start on room creation) or a sample that records only the LiveAvatar track, I can provide that too.
Which output/target do you want first (MP4→S3, HLS→S3, or MP4→Azure)? I’ll give a ready-to-run Node.js snippet for your chosen option including request/response handling and StopEgress.icy-beard-64788
12/05/2025, 4:32 PMtall-airline-16756
12/05/2025, 4:32 PMsessions/start response contains the LiveKit connection details you need on the client. I’ll clarify where each value comes from and what you need on the backend to start Egress recording.
What each field is and where to use it
• livekit_url — the LiveKit server URL to connect to (use this in the frontend LiveKitRoom serverUrl or when creating a RoomServiceClient on the backend).
• livekit_client_token — short‑lived token for the client to join the room (use this in your frontend token prop).
• session_id / ws_url — LiveAvatar session identifiers/WS endpoint (keep for session management; not required to start egress).
• API key / API secret for Egress — separate from the client token. You must use an API key/secret with roomRecord permission from your LiveKit project (or LiveKit Cloud project) to call the Egress API from your backend.
Where to get keys/URLs
• LiveAvatar / LiveKit Cloud dashboard: retrieve or generate the LiveKit API key and secret for your project (the key/secret used server‑side to start Egress). The livekit_url and livekit_client_token are returned by the LiveAvatar sessions/start response; use those on the client to connect.
• If you’re self‑hosting LiveKit, use your server address as livekit_url and create an API key/secret with roomRecord permissions in your LiveKit admin.
Minimal flow to record (summary)
1. Frontend: call LiveAvatar sessions/start (your example curl). Use livekit_client_token and livekit_url to render LiveKitRoom.
2. Backend (Node.js): use your LiveKit API key/secret (server credentials) to call the Egress API (Room Composite) and write to S3/Azure. This is separate from the client token returned by LiveAvatar.
3. Stop egress via StopEgress when done or let it stop automatically.
Node.js Egress example (fill in placeholders)
import { RoomServiceClient } from 'livekit-server-sdk';
const svc = new RoomServiceClient('wss://<LIVEKIT_SERVER>', '<API_KEY>', '<API_SECRET>');
await svc.startRoomCompositeEgress('<room-name>', {
layout: 'grid',
audioOnly: false,
fileOutputs: [{
filepath: 'recordings/session.mp4',
s3: {
bucket: '<BUCKET>',
accessKey: '<S3_KEY>',
secret: '<S3_SECRET>',
region: '<REGION>',
},
}],
});
Quick checklist for you to confirm
• Do you have access to the LiveAvatar response that includes livekit_url and livekit_client_token? (That’s what the client uses.)
• Do you have a server API key/secret with roomRecord permission from your LiveKit project or Cloud dashboard? (That’s what the backend uses to start Egress.)
• Which storage target do you want to use first (S3 or Azure)? I’ll give the exact Node.js snippet with the correct output block and StopEgress example.
Tell me which storage target to show first and whether you can access your project API key/secret in the LiveKit/LiveAvatar dashboard.icy-beard-64788
12/05/2025, 4:33 PMtall-airline-16756
12/05/2025, 4:33 PMsessions/start response — use livekit_url as the server URL in your frontend LiveKitRoom and livekit_client_token as the client token.
• API key & API secret (server credentials): get these from your LiveKit project (LiveKit Cloud or self‑hosted admin/dashboard). Use the key/secret on your backend to call Egress. Ensure the key has the roomRecord permission.
• ws_url: LiveAvatar may return a ws_url for session control; your backend doesn’t need it to start Egress. For LiveKit server SDKs, use the livekit_url (or your LiveKit dashboard URL) when creating RoomServiceClient.
Ready-to-use checklist for your Node.js backend:
1. In LiveKit dashboard: create/get an API key + secret with roomRecord permission.
2. In your backend code, create RoomServiceClient with your LiveKit server URL and API key/secret.
3. Call startRoomCompositeEgress(...) with desired output (MP4/HLS) and S3/Azure config.
4. Use the returned egress_id to stop recording if needed.
If you want, tell me which storage target (S3 or Azure) you want to implement first and I’ll paste a complete ready-to-run Node.js snippet with error handling and StopEgress.icy-beard-64788
12/05/2025, 4:35 PMtall-airline-16756
12/05/2025, 4:35 PMws_url is null. That’s fine: you only need livekit_url + livekit_client_token for the frontend, and a separate server API key/secret for Egress.
Quick confirmation and next step:
• Confirmed: ws_url is not needed to start Egress.
• Frontend uses: livekit_url (serverUrl) and livekit_client_token (token).
• Backend uses: LiveKit API key & secret (from your LiveKit dashboard) + the same room name that the client joins to start Egress.
Which storage target should I provide the ready-to-run Node.js snippet for first — S3 or Azure Blob?icy-beard-64788
12/05/2025, 4:35 PMtall-airline-16756
12/05/2025, 4:35 PMsessions/start response fields — some integrations include session_id or a room field you can use directly as the room name. If LiveAvatar set a room name at creation, use that.
1. Decode the livekit_client_token
• The livekit_client_token is a JWT. It often contains a room (or room_name) claim you can read to get the room name.
Quick Node.js example to decode the token (no verification needed just to read claims):
const jwt = require('jsonwebtoken');
const token = '<livekit_client_token>';
const decoded = jwt.decode(token);
console.log(decoded); // look for decoded.room or decoded.room_name
Notes
• If you control the LiveAvatar session creation, you can supply a custom room name there (recommended for predictable naming).
• The room name you use for Egress must match the room clients join.
• If the token has no room claim and LiveAvatar response contains no room, ask your LiveAvatar flow what room name it assigns (or configure it to set one).
Tell me whether you want the S3 or Azure Node.js egress snippet next and I’ll include using the exact room name you get from the token/response.icy-beard-64788
12/05/2025, 4:37 PMsession_idtall-airline-16756
12/05/2025, 4:37 PMsession_id from LiveAvatar is not necessarily the LiveKit room name. To get the room name you should:
1. Decode the livekit_client_token JWT and look for a room or room_name claim.
const jwt = require('jsonwebtoken');
const decoded = jwt.decode('<livekit_client_token>');
console.log(decoded); // look for decoded.room or decoded.room_name
1. If the token has no room claim, check the LiveAvatar sessions/start response for a room field or configure LiveAvatar to set a specific room name when creating the session.
Use that exact room name in your backend when calling startRoomCompositeEgress(...).
Which storage target do you want the ready-to-run Node.js egress snippet for first — S3 or Azure?icy-beard-64788
12/05/2025, 4:44 PMtall-airline-16756
12/05/2025, 4:44 PMroom_id: "RM_YxcnGaXotX9f". Use that value as the LiveKit room name when starting Egress from your backend.
Next, tell me:
• Which storage target do you want first: S3 or Azure Blob?
• Which output format: MP4 or HLS?
I’ll give a ready-to-run Node.js snippet (start + stop egress) using that room ID and your chosen storage.icy-beard-64788
12/05/2025, 4:45 PMtall-airline-16756
12/05/2025, 4:45 PMRM_YxcnGaXotX9f room ID.icy-beard-64788
12/05/2025, 4:45 PMtall-airline-16756
12/05/2025, 4:45 PMRM_YxcnGaXotX9f.
Before you run:
• Ensure you have a LiveKit API key/secret with the roomRecord permission.
• Install the server SDK: npm install livekit-server-sdk.
• Make sure your S3 creds have write access to the target bucket.
Start Egress (MP4 → S3)
// start-egress.ts
import { RoomServiceClient } from 'livekit-server-sdk';
const LIVEKIT_WS = 'wss://<YOUR_LIVEKIT_HOST>'; // e.g. wss://your-project.livekit.cloud
const API_KEY = process.env.LIVEKIT_API_KEY!;
const API_SECRET = process.env.LIVEKIT_API_SECRET!;
const svc = new RoomServiceClient(LIVEKIT_WS, API_KEY, API_SECRET);
async function startEgress() {
const roomName = 'RM_YxcnGaXotX9f';
const resp = await svc.startRoomCompositeEgress(roomName, {
layout: 'grid', // or 'speaker', 'single-speaker'
audioOnly: false, // false => include audio + video
fileOutputs: [{
filepath: 'recordings/session.mp4',
s3: {
bucket: 'your-s3-bucket',
accessKey: process.env.S3_ACCESS_KEY!,
secret: process.env.S3_SECRET!,
region: 'us-east-1',
},
}],
});
console.log('Egress started:', resp.egressId || resp.egress_id || resp);
return resp;
}
startEgress().catch((err) => {
console.error('startEgress error', err);
process.exit(1);
});
Stop Egress (by egress_id returned above)
// stop-egress.ts
import { RoomServiceClient } from 'livekit-server-sdk';
const LIVEKIT_WS = 'wss://<YOUR_LIVEKIT_HOST>';
const API_KEY = process.env.LIVEKIT_API_KEY!;
const API_SECRET = process.env.LIVEKIT_API_SECRET!;
const svc = new RoomServiceClient(LIVEKIT_WS, API_KEY, API_SECRET);
async function stopEgress(egressId: string) {
const resp = await svc.stopEgress(egressId);
console.log('Egress stopped:', resp);
}
const egressId = process.argv[2];
if (!egressId) {
console.error('Usage: node stop-egress.js <egressId>');
process.exit(1);
}
stopEgress(egressId).catch((err) => {
console.error('stopEgress error', err);
process.exit(1);
});
Notes and tips
• The startRoomCompositeEgress response includes an egressId (store it to stop later).
• S3 filepath is the path within the bucket (the SDK manages uploading).
• If you prefer HLS later, change the request to include an hls block instead of fileOutputs.
• If you want audio-only, set audioOnly: true.
• Use HTTPS/WSS host from your LiveKit dashboard as LIVEKIT_WS.
• Ensure environment variables are set: LIVEKIT_API_KEY, LIVEKIT_API_SECRET, S3_ACCESS_KEY, S3_SECRET.
Want me to:
• Return a version that writes logs and retries on failure?
• Convert this to an Express endpoint that starts/stops egress via HTTP?icy-beard-64788
12/05/2025, 4:47 PMtall-airline-16756
12/05/2025, 4:47 PMlivekit_client_token or session_id — those are only for clients to join the room.
• Temporary creds: if you use AWS STS (temporary credentials), pass the sessionToken along with accessKey/secret in the egress S3 block.
• Security: keep S3 credentials only on your backend (never in browser/client). Use IAM roles or short‑lived STS creds for better security.
If you want, I can show the exact Node.js egress snippet using temporary STS credentials (including sessionToken) or standard accessKey/secret — which do you prefer?icy-beard-64788
12/05/2025, 4:48 PMtall-airline-16756
12/05/2025, 4:48 PMnpm install livekit-server-sdk @aws-sdk/client-sts @aws-sdk/credential-providers
2) start-egress-with-sts.ts
import { RoomServiceClient } from 'livekit-server-sdk';
import { STSClient, AssumeRoleCommand } from '@aws-sdk/client-sts';
const LIVEKIT_WS = process.env.LIVEKIT_WS!; // e.g. wss://your-project.livekit.cloud
const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY!;
const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET!;
const ROLE_ARN = process.env.AWS_ASSUME_ROLE_ARN!; // role with S3 write permissions
const S3_BUCKET = process.env.S3_BUCKET!;
async function assumeRole() {
const client = new STSClient({});
const cmd = new AssumeRoleCommand({
RoleArn: ROLE_ARN,
RoleSessionName: 'livekit-egress-session',
DurationSeconds: 3600, // adjust as needed
});
const res = await client.send(cmd);
if (!res.Credentials) throw new Error('Failed to assume role');
return {
accessKeyId: res.Credentials.AccessKeyId!,
secretAccessKey: res.Credentials.SecretAccessKey!,
sessionToken: res.Credentials.SessionToken!,
};
}
async function startEgress() {
// assume role to get temporary S3 creds
const { accessKeyId, secretAccessKey, sessionToken } = await assumeRole();
// create LiveKit RoomService client
const svc = new RoomServiceClient(LIVEKIT_WS, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
const roomName = 'RM_YxcnGaXotX9f'; // your room ID from decoded token
const resp = await svc.startRoomCompositeEgress(roomName, {
layout: 'grid',
audioOnly: false, // include audio + video
fileOutputs: [{
filepath: 'recordings/session.mp4',
s3: {
bucket: S3_BUCKET,
accessKey: accessKeyId,
secret: secretAccessKey,
region: process.env.AWS_REGION || 'us-east-1',
sessionToken: sessionToken, // include the STS session token
},
}],
});
console.log('Egress started:', resp.egressId || resp.egress_id || resp);
return resp.egressId || resp.egress_id;
}
startEgress().then(id => {
console.log('Use this egressId to stop:', id);
}).catch(err => {
console.error(err);
process.exit(1);
});
3) stop-egress.ts
import { RoomServiceClient } from 'livekit-server-sdk';
const LIVEKIT_WS = process.env.LIVEKIT_WS!;
const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY!;
const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET!;
const svc = new RoomServiceClient(LIVEKIT_WS, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
async function stopEgress(egressId: string) {
const res = await svc.stopEgress(egressId);
console.log('Stopped egress:', res);
}
const egressId = process.argv[2];
if (!egressId) {
console.error('Usage: node stop-egress.js <egressId>');
process.exit(1);
}
stopEgress(egressId).catch(err => {
console.error(err);
process.exit(1);
});
Environment variables to set:
• LIVEKIT_WS (wss://... from LiveKit dashboard)
• LIVEKIT_API_KEY and LIVEKIT_API_SECRET (server credentials with roomRecord permission)
• AWS_ASSUME_ROLE_ARN (ARN of the role that has S3 PutObject permissions)
• S3_BUCKET
• AWS_REGION (optional)
IAM tips:
• The role you assume should allow PutObject and PutObjectAcl (if needed) on the target S3 prefix.
• If you prefer, you can also use an IAM user accessKey/secret directly (omit sessionToken) — STS is recommended for security.
Would you like this as an Express endpoint (start/stop via HTTP) or with automatic StopEgress after a timeout?icy-beard-64788
12/05/2025, 4:51 PMtall-airline-16756
12/05/2025, 4:51 PMicy-beard-64788
12/05/2025, 4:55 PMtall-airline-16756
12/05/2025, 4:55 PMlivekit_url + livekit_client_token.
• When your front end is ready to start recording, call your backend endpoint (not LiveKit directly from the browser).
• Backend: assumes role / gets S3 temporary creds (or uses long‑term creds), then calls LiveKit Egress (startRoomCompositeEgress) with the room name and S3 creds.
• LiveKit Egress records the room and uploads the MP4 directly to your S3 bucket.
• Backend stores the returned egressId so you can stop the recording later (or stop automatically).
Minimal frontend fetch example (call your backend when UI starts recording)
// from your React app when you want to start recording
await fetch('/api/start-recording', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ room: 'RM_YxcnGaXotX9f' }) });
Backend responsibilities
1. Optionally assume AWS role (STS) to get temp S3 creds.
2. Call LiveKit RoomServiceClient.startRoomCompositeEgress(roomName, { fileOutputs: [{ s3: { accessKey, secret, sessionToken, bucket, region }, filepath: 'recordings/session.mp4' }], audioOnly:false, layout:'grid' })
3. Return or persist the egressId to allow stopping later.
4. Provide an endpoint to stop egress (calls stopEgress with egressId).
If you want, I’ll give a full ready-to-run Express pair of endpoints (/api/start-recording and /api/stop-recording) that:
• assumes role for STS,
• starts Room Composite MP4 egress to S3,
• returns/saves the egressId,
and includes basic error handling. Should I provide that now?icy-beard-64788
12/05/2025, 4:57 PMtall-airline-16756
12/05/2025, 4:57 PMLiveKitRoom, the client disconnects but the agent/avatar can remain in the LiveKit room.
• That means the avatar and agent may keep running (and egress may keep recording) unless you explicitly stop them.
What you should do
• Best practice: when the user leaves, call your backend to delete the LiveKit room (or stop the AgentSession). Deleting the room will:
◦ Disconnect the agent and avatar,
◦ Stop any active egress recordings,
◦ Cleanly end the LiveAvatar session.
How to implement (minimal)
1. Frontend: on leave/unmount, call your backend endpoint:
fetch('/api/end-session', { method: 'POST', body: JSON.stringify({ room: 'RM_YxcnGaXotX9f' }) });
1. Backend: delete the room using RoomServiceClient:
import { RoomServiceClient } from 'livekit-server-sdk';
const svc = new RoomServiceClient(LIVEKIT_WS, LIVEKIT_API_KEY, LIVEKIT_API_SECRET);
await svc.deleteRoom('RM_YxcnGaXotX9f');
Alternative
• If you prefer not to delete the room, call your agent logic to stop the AgentSession (e.g., session.aclose()), or call stopEgress(egressId) to stop recordings while keeping the room.
Recommendation
• Delete the room on user disconnect for a clean shutdown (recommended).
Would you like the Express endpoints for /api/end-session (delete room) and /api/start-recording wired together?
Sources: Job lifecycle | LiveKit docs | RoomComposite Egress | LiveKit Docs | Egress output types | LiveKit docs | Web Egress | LiveKit Docs | Virtual avatar plugins | LiveKit Docsicy-beard-64788
12/05/2025, 4:59 PMtall-airline-16756
12/05/2025, 4:59 PM// inside VideoConference component
async function handleExit() {
await fetch('/api/end-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room: 'RM_YxcnGaXotX9f' }),
});
// then navigate away / cleanup client UI
// e.g., window.location = '/goodbye' or update app state
}
// render
<button onClick={handleExit}>Exit</button>
2) Backend: delete the LiveKit room (stops avatar/agent and any egress)
• Implement /api/end-session to call RoomServiceClient.deleteRoom with your server API key/secret.
Example (Express + Node.js):
// server.js (or routes file)
import express from 'express';
import { RoomServiceClient } from 'livekit-server-sdk';
const app = express();
app.use(express.json());
const svc = new RoomServiceClient(process.env.LIVEKIT_WS!, process.env.LIVEKIT_API_KEY!, process.env.LIVEKIT_API_SECRET!);
app.post('/api/end-session', async (req, res) => {
const { room } = req.body;
if (!room) return res.status(400).json({ error: 'room required' });
try {
await svc.deleteRoom(room);
return res.json({ ok: true });
} catch (err) {
console.error('deleteRoom error', err);
return res.status(500).json({ error: 'failed to delete room' });
}
});
app.listen(3000);
Why this works
• Deleting the room disconnects all participants, stops the LiveAvatar/agent, and automatically ends any Room Composite egress. It avoids lingering avatar activity or extra recordings.
Extras / best practices
• Confirm the frontend only calls the endpoint after local cleanup (stop local tracks, unmount LiveKitRoom).
• Protect the endpoint (authenticate the caller) so only authorized users can delete rooms.
• Optionally return the current egressId or egress status from the backend if you need to show recording state to the user.
Would you like a full example that:
• unmounts LiveKitRoom, stops local tracks, then calls /api/end-session, or
• includes auth on the endpoint?icy-beard-64788
12/05/2025, 5:00 PMtall-airline-16756
12/05/2025, 5:00 PMimport { useRoom } from '@livekit/react'; // or useRoomContext hook your SDK provides
import { useEffect } from 'react';
function VideoConferenceWrapper({ roomName }) {
const room = useRoom(); // or useRoomContext() depending on your SDK
// call backend to end session
async function endSession() {
try {
await fetch('/api/end-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room: roomName }),
});
} catch (err) {
console.error('endSession error', err);
}
}
// Exit button handler
async function handleExit() {
// stop local tracks / cleanup client UI first (optional)
try {
room?.localParticipant?.stopPublishing?.(); // optional safe cleanup if available
} catch {}
// unmount LiveKitRoom (navigate away) then tell backend to delete room
await endSession();
// navigate away or update state to remove LiveKitRoom
window.location.href = '/';
}
// Detect disconnect (network or client leaving) and call backend cleanup
useEffect(() => {
if (!room) return;
const onDisconnected = () => {
endSession();
};
room.on('disconnected', onDisconnected); // event name may be 'disconnected' or 'connectionStateChanged' depending on SDK
// also handle page unload as a fallback
const onUnload = () => { navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName })); };
window.addEventListener('beforeunload', onUnload);
return () => {
room.off?.('disconnected', onDisconnected);
window.removeEventListener('beforeunload', onUnload);
};
}, [room, roomName]);
return (
<>
<VideoConference />
<button onClick={handleExit}>Exit</button>
</>
);
}
Backend endpoint (Express example — deletes the LiveKit room)
import express from 'express';
import { RoomServiceClient } from 'livekit-server-sdk';
const app = express();
app.use(express.json());
const svc = new RoomServiceClient(process.env.LIVEKIT_WS!, process.env.LIVEKIT_API_KEY!, process.env.LIVEKIT_API_SECRET!);
app.post('/api/end-session', async (req, res) => {
const { room } = req.body;
if (!room) return res.status(400).send({ error: 'room required' });
try {
await svc.deleteRoom(room);
return res.json({ ok: true });
} catch (err) {
console.error('deleteRoom error', err);
return res.status(500).json({ error: 'failed to delete room' });
}
});
Notes
• Use the decoded room_id (e.g., RM_YxcnGaXotX9f) as roomName.
• Protect /api/end-session (authenticate requests) so only authorized users can delete rooms.
• Deleting the room will stop the LiveAvatar/agent and any active egress automatically.
• Use navigator.sendBeacon on unload to improve delivery reliability for quick disconnects.
If you want, I can adapt the React snippet to your exact LiveKit React SDK hooks (showing the exact event name and local track cleanup) — tell me which LiveKit React package/version you’re using.icy-beard-64788
12/05/2025, 5:04 PMtall-airline-16756
12/05/2025, 5:05 PMserverUrl, token, and roomName as props (you already decode the token to get roomName).
• Protect backend /api/end-session so only authorized callers can delete the room.
File: VideoRoom.tsx
import React, { useEffect, useState } from 'react';
import {
LiveKitRoom,
RoomAudioRenderer,
useParticipants,
VideoTrack,
Participant,
useRoomContext,
} from '@livekit/components-react';
import '@livekit/components-styles';
type VideoRoomProps = {
serverUrl: string;
token: string;
roomName: string; // e.g. RM_YxcnGaXotX9f
onEnded?: () => void;
};
export default function VideoRoom({ serverUrl, token, roomName, onEnded }: VideoRoomProps) {
return (
<LiveKitRoom
serverUrl={serverUrl}
token={token}
connect={true}
audio={true}
video={true}
style={{ height: '70vh', width: '70vw', background: '#000' }}
>
<RoomUI roomName={roomName} onEnded={onEnded} />
<RoomAudioRenderer />
</LiveKitRoom>
);
}
function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
const participants = useParticipants();
const [egressId, setEgressId] = useState<string | null>(null);
// Identify local user and agent participant
const local = participants.find(p => p.isLocal);
// Heuristic: LiveAvatar agent often has identity prefix/suffix; adjust if needed.
const agent = participants.find(p => /agent|avatar/i.test(p.identity));
// Exit handler: call backend to delete room, then navigate/unmount
async function handleExit() {
try {
// optional: stop local tracks/cleanup here if needed
await fetch('/api/end-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room: roomName, egressId }),
});
} catch (err) {
console.error('end-session error', err);
} finally {
if (onEnded) onEnded();
else window.location.href = '/';
}
}
// Optional: detect unmount/disconnect and call end-session via sendBeacon
useEffect(() => {
const onUnload = () => {
try {
navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName, egressId }));
} catch {}
};
window.addEventListener('beforeunload', onUnload);
return () => window.removeEventListener('beforeunload', onUnload);
}, [roomName, egressId]);
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<div style={{ display: 'flex', gap: 12, flex: 1 }}>
<ParticipantPanel title="You" participant={local} />
<ParticipantPanel title="AI Agent" participant={agent} placeholder="Agent connecting..." />
</div>
<div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
<button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
</div>
</div>
);
}
function ParticipantPanel({
participant,
title,
placeholder = 'No video',
}: {
participant?: Participant;
title: string;
placeholder?: string;
}) {
// If we have an attached video track publication, VideoTrack component will render it.
// VideoTrack accepts a trackRef: publication or track reference; components library handles it.
return (
<div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
<div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{participant ? (
// VideoTrack will auto-render the participant's first camera track if available
// Provide participant to VideoTrack via trackRef APIs; components lib handles subscriptions.
// Using <VideoTrack publication={...} /> is an option, but passing participant here is fine for simplicity.
<VideoTrack participant={participant} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<div style={{
color: '#ddd',
textAlign: 'center',
padding: 16,
}}>{placeholder}</div>
)}
</div>
</div>
);
}
How it works
• LiveKitRoom handles connection with the provided serverUrl and token.
• useParticipants returns current participants; we pick local.isLocal for the user and find the agent by identity matching "agent" or "avatar".
• VideoTrack renders each participant's camera track and RoomAudioRenderer plays all audio.
• Exit button calls /api/end-session with the room name (backend should call RoomServiceClient.deleteRoom(roomName)).
Notes / tuning
• Participant detection: adjust the agent identity heuristic to whatever LiveAvatar uses in your project (e.g., startsWith('agent-avatar')).
• If you prefer explicit track rendering, find the camera publication via participant.getTrack(Track.Source.Camera) and pass that to VideoTrack publication prop.
• Protect /api/end-session and authenticate the caller.
• If you want the Exit button to also stop local tracks before deleting the room, call participant.localParticipant?.unpublishTrack(...) or stop tracks locally before calling the backend.
Want this adapted to:
• raw livekit-client hooks (no @livekit/components-react), or
• include a start/stop recording button that calls your backend endpoints to start Egress?
Which would you like next?
Sources: LiveAvatar virtual avatar integration guide | LiveKit docs | Bringing AI avatars to voice agents | Bringing AI avatars to voice agents | Subscribing to tracks | LiveKit docsicy-beard-64788
12/05/2025, 5:12 PMtall-airline-16756
12/05/2025, 5:13 PMParticipant is exported from livekit-client, not @livekit/components-react. Below is a corrected, minimal TypeScript React component that:
• Uses correct imports
• Renders two panels: local user and LiveAvatar agent
• Uses useParticipants() from @livekit/components-react
• Uses VideoTrack to render participant video
• Includes an Exit button that calls your backend to delete the room
Drop-in file: VideoRoom.tsx
import React, { useEffect, useState } from 'react';
import { Participant } from 'livekit-client';
import {
LiveKitRoom,
RoomAudioRenderer,
useParticipants,
VideoTrack,
} from '@livekit/components-react';
import '@livekit/components-styles';
type VideoRoomProps = {
serverUrl: string;
token: string;
roomName: string; // e.g. RM_YxcnGaXotX9f
onEnded?: () => void;
};
export default function VideoRoom({ serverUrl, token, roomName, onEnded }: VideoRoomProps) {
return (
<LiveKitRoom
serverUrl={serverUrl}
token={token}
connect={true}
audio={true}
video={true}
style={{ height: '70vh', width: '70vw', background: '#000' }}
>
<RoomUI roomName={roomName} onEnded={onEnded} />
<RoomAudioRenderer />
</LiveKitRoom>
);
}
function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
const participants = useParticipants();
const [egressId, setEgressId] = useState<string | null>(null);
const local = participants.find(p => p.isLocal) as Participant | undefined;
const agent = participants.find(p => /agent|avatar/i.test(p.identity)) as Participant | undefined;
async function handleExit() {
try {
await fetch('/api/end-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room: roomName, egressId }),
});
} catch (err) {
console.error('end-session error', err);
} finally {
if (onEnded) onEnded();
else window.location.href = '/';
}
}
useEffect(() => {
const onUnload = () => {
try {
navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName, egressId }));
} catch {}
};
window.addEventListener('beforeunload', onUnload);
return () => window.removeEventListener('beforeunload', onUnload);
}, [roomName, egressId]);
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<div style={{ display: 'flex', gap: 12, flex: 1 }}>
<ParticipantPanel title="You" participant={local} />
<ParticipantPanel title="AI Agent" participant={agent} placeholder="Agent connecting..." />
</div>
<div style={{ marginTop: 8, display: 'flex', gap: 8 }}>
<button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
</div>
</div>
);
}
function ParticipantPanel({
participant,
title,
placeholder = 'No video',
}: {
participant?: Participant;
title: string;
placeholder?: string;
}) {
return (
<div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
<div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{participant ? (
<VideoTrack participant={participant} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<div style={{ color: '#ddd', textAlign: 'center', padding: 16 }}>{placeholder}</div>
)}
</div>
</div>
);
}
Notes
• Adjust the agent identity detection (/agent|avatar/i) to match your LiveAvatar identity scheme.
• If you prefer to render a specific publication, use participant.getTrack(Track.Source.Camera) from livekit-client and pass the publication to VideoTrack.
• Protect /api/end-session on the backend so only authorized users can delete rooms.
Would you like the variant that selects camera publication explicitly (with Track imports) or an example without @livekit/components-react using raw hooks?icy-beard-64788
12/05/2025, 5:16 PMtall-airline-16756
12/05/2025, 5:17 PMVideoTrack expects a trackRef (a TrackReference) or a publication/track, not a Participant. Use useTracks (or get the participant's camera publication) to produce a TrackReference and pass it as trackRef.
Minimal TypeScript React example (local user + LiveAvatar agent, Exit button, backend call):
import React, { useEffect } from 'react';
import { Participant, Track } from 'livekit-client';
import {
LiveKitRoom,
RoomAudioRenderer,
useParticipants,
useTracks,
VideoTrack,
} from '@livekit/components-react';
import '@livekit/components-styles';
type VideoRoomProps = {
serverUrl: string;
token: string;
roomName: string;
onEnded?: () => void;
};
export default function VideoRoom({ serverUrl, token, roomName, onEnded }: VideoRoomProps) {
return (
<LiveKitRoom
serverUrl={serverUrl}
token={token}
connect={true}
audio={true}
video={true}
style={{ height: '70vh', width: '70vw', background: '#000' }}
>
<RoomUI roomName={roomName} onEnded={onEnded} />
<RoomAudioRenderer />
</LiveKitRoom>
);
}
function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
const participants = useParticipants();
const local = participants.find(p => p.isLocal) as Participant | undefined;
const agent = participants.find(p => /agent|avatar/i.test(p.identity)) as Participant | undefined;
// Get camera track refs for local and agent (onlySubscribed: false so it works immediately)
const localTracks = useTracks([{ participant: local, source: Track.Source.Camera }], { onlySubscribed: false });
const agentTracks = useTracks([{ participant: agent, source: Track.Source.Camera }], { onlySubscribed: false });
const localVideo = localTracks[0]; // TrackReference | undefined
const agentVideo = agentTracks[0];
async function handleExit() {
try {
// optional: stop local tracks locally
local?.getTracks().forEach(t => t.stop?.());
await fetch('/api/end-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room: roomName }),
});
} catch (err) {
console.error('end-session error', err);
} finally {
if (onEnded) onEnded();
else window.location.href = '/';
}
}
useEffect(() => {
const onUnload = () => {
try {
navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName }));
} catch {}
};
window.addEventListener('beforeunload', onUnload);
return () => window.removeEventListener('beforeunload', onUnload);
}, [roomName]);
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<div style={{ display: 'flex', gap: 12, flex: 1 }}>
<ParticipantPanel title="You" trackRef={localVideo} placeholder="Your camera off" />
<ParticipantPanel title="AI Agent" trackRef={agentVideo} placeholder="Agent connecting..." />
</div>
<div style={{ marginTop: 8 }}>
<button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
</div>
</div>
);
}
function ParticipantPanel({ title, trackRef, placeholder = 'No video' }: { title: string; trackRef?: any; placeholder?: string }) {
return (
<div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
<div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{trackRef ? (
<VideoTrack trackRef={trackRef} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<div style={{ color: '#ddd', textAlign: 'center', padding: 16 }}>{placeholder}</div>
)}
</div>
</div>
);
}
Notes:
• Use useTracks to get a TrackReference and pass it as trackRef to VideoTrack.
• onlySubscribed: false lets you get the publication even before subscription—adjust to your needs.
• If you prefer to pull the publication directly, use participant.getTrackPublication(Track.Source.Camera) and convert to a TrackReference the component accepts.
• Protect /api/end-session on the backend.
Want a variant that explicitly finds the camera publication (without useTracks) or an example using raw livekit-client hooks?
Sources: Handling events | LiveKit docs | Rooms, participants, and tracks | LiveKit docsicy-beard-64788
12/05/2025, 5:18 PMtall-airline-16756
12/05/2025, 5:18 PMuseTracks expects track source configs (not participant objects) and VideoTrack requires a trackRef (a TrackReference), not a participant. Below is a corrected, minimal TypeScript React component that:
• uses useParticipants() to find local and agent participants
• builds TrackReference objects from each participant's camera publication
• passes those TrackReference(s) to VideoTrack
• includes an Exit button that calls your backend to delete the room
Drop-in file: VideoRoom.tsx
import React, { useEffect } from 'react';
import { Participant, Track } from 'livekit-client';
import {
LiveKitRoom,
RoomAudioRenderer,
useParticipants,
useTracks,
VideoTrack,
TrackReference,
} from '@livekit/components-react';
import '@livekit/components-styles';
type Props = {
serverUrl: string;
token: string;
roomName: string;
onEnded?: () => void;
};
export default function VideoRoom({ serverUrl, token, roomName, onEnded }: Props) {
return (
<LiveKitRoom
serverUrl={serverUrl}
token={token}
connect={true}
audio={true}
video={true}
style={{ height: '70vh', width: '70vw', background: '#000' }}
>
<RoomUI roomName={roomName} onEnded={onEnded} />
<RoomAudioRenderer />
</LiveKitRoom>
);
}
function RoomUI({ roomName, onEnded }: { roomName: string; onEnded?: () => void }) {
const participants = useParticipants();
// find local and agent participants
const local = participants.find(p => p.isLocal) as Participant | undefined;
const agent = participants.find(p => /agent|avatar/i.test(p.identity)) as Participant | undefined;
// Use useTracks to get all camera TrackReferences (optional, not required here)
// const cameraRefs = useTracks([{ source: Track.Source.Camera }], { onlySubscribed: false });
// Build TrackReference for a participant's camera publication (if present)
const makeTrackRef = (p?: Participant): TrackReference | undefined => {
if (!p) return undefined;
const pub = p.getTrackPublication(Track.Source.Camera);
if (!pub) return undefined;
// TrackReference shape the VideoTrack expects: { participant, publication, source }
return { participant: p, publication: pub, source: Track.Source.Camera } as TrackReference;
};
const localTrackRef = makeTrackRef(local);
const agentTrackRef = makeTrackRef(agent);
async function handleExit() {
try {
// stop local tracks locally
local?.getTracks().forEach(t => t.stop?.());
await fetch('/api/end-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ room: roomName }),
});
} catch (err) {
console.error('end-session error', err);
} finally {
if (onEnded) onEnded();
else window.location.href = '/';
}
}
useEffect(() => {
const onUnload = () => {
try {
navigator.sendBeacon('/api/end-session', JSON.stringify({ room: roomName }));
} catch {}
};
window.addEventListener('beforeunload', onUnload);
return () => window.removeEventListener('beforeunload', onUnload);
}, [roomName]);
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
<div style={{ display: 'flex', gap: 12, flex: 1 }}>
<ParticipantPanel title="You" trackRef={localTrackRef} placeholder="Your camera off" />
<ParticipantPanel title="AI Agent" trackRef={agentTrackRef} placeholder="Agent connecting..." />
</div>
<div style={{ marginTop: 8 }}>
<button onClick={handleExit} style={{ padding: '8px 12px' }}>Exit</button>
</div>
</div>
);
}
function ParticipantPanel({ title, trackRef, placeholder = 'No video' }: { title: string; trackRef?: TrackReference; placeholder?: string }) {
return (
<div style={{ flex: 1, position: 'relative', background: '#111', borderRadius: 8, overflow: 'hidden' }}>
<div style={{ position: 'absolute', top: 8, left: 8, color: '#fff', zIndex: 5 }}>{title}</div>
<div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{trackRef ? (
<VideoTrack trackRef={trackRef} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
) : (
<div style={{ color: '#ddd', textAlign: 'center', padding: 16 }}>{placeholder}</div>
)}
</div>
</div>
);
}
Notes
• The key fix: create a TrackReference from the participant's camera publication and pass it as trackRef to VideoTrack. Passing a raw Participant causes the TypeScript error.
• If getTrackPublication(Track.Source.Camera) returns undefined (participant not publishing camera), show placeholder or use useTracks([{ source: Track.Source.Camera }]) to find available camera tracks.
• Adjust the agent identity detection regex to match your environment.
• Keep /api/end-session protected and running on your backend to call LiveKit's RoomServiceClient.deleteRoom.
If you want, I can:
• provide a variant that uses useTracks to list all camera tracks and maps them to panels, or
• convert this into a version without @livekit/components-react using raw livekit-client hooks. Which would you prefer? Sources: Subscribing to tracks | LiveKit docs | Handling events | LiveKit docs | Expo quickstart | LiveKit docs | Virtual avatar plugins | LiveKit Docs