### Quick Start: Initialize and Connect to a LiveKit Room Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/INDEX.md This snippet demonstrates the basic setup for initializing a LiveKit room with default options, setting up event listeners for connection and track subscription, connecting to a server, publishing local media, and handling disconnections. ```typescript import { Room, VideoPresets, RoomEvent } from 'livekit-client'; // Create room with defaults const room = new Room({ adaptiveStream: true, dynacast: true, videoCaptureDefaults: { resolution: VideoPresets.h720.resolution, }, }); // Set up event listeners room.on(RoomEvent.Connected, () => { console.log('Connected to room:', room.name); }); room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => { const element = track.attach(); document.body.appendChild(element); }); // Connect to server await room.connect('ws://localhost:7800', token); // Publish local media await room.localParticipant.enableCameraAndMicrophone(); // Cleanup on disconnect room.on(RoomEvent.Disconnected, () => { room.localParticipant.tracks.forEach(pub => { pub.track?.stop(); }); }); ``` -------------------------------- ### Real-time Data Synchronization Example Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/data-and-rpc-api.md This example demonstrates how to initialize real-time data synchronization within a LiveKit room. It covers creating a local data track, publishing it, subscribing to remote data tracks, and handling incoming data and commands. ```typescript import { Room, RemoteDataTrack, RoomEvent } from 'livekit-client'; class RealtimeDataSync { private room: Room; private dataTrack: LocalDataTrack; async initialize(room: Room) { this.room = room; // Create data track for publishing this.dataTrack = new LocalDataTrack({ name: 'realtime-sync', }); await this.room.localParticipant!.publishTrack(this.dataTrack); // Subscribe to remote data this.room.on(RoomEvent.TrackSubscribed, (track) => { if (track instanceof RemoteDataTrack) { track.onData = this.handleRemoteData.bind(this); } }); // Register text stream for commands this.room.registerTextStreamHandler('commands', (cmd) => { this.handleCommand(cmd); }); } async sendUpdate(data: any) { const packet = { type: 'update', data, timestamp: Date.now(), }; this.dataTrack.sendData( new TextEncoder().encode(JSON.stringify(packet)) ); } private handleRemoteData(data: Uint8Array) { try { const message = new TextDecoder().decode(data); const packet = JSON.parse(message); console.log('Received:', packet); } catch (error) { console.error('Failed to parse data:', error); } } private handleCommand(cmd: string) { const { action, payload } = JSON.parse(cmd); console.log(`Command: ${action}`, payload); } } ``` -------------------------------- ### Complete Error Handling and Recovery Example Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/errors-reference.md A comprehensive example demonstrating how to handle connection errors, media device errors, and RPC errors, including reconnection logic and device/track recovery. ```typescript import { Room, RoomEvent, ConnectionError, ConnectionErrorReason, DeviceUnsupportedError, MediaDeviceFailure, RpcError, } from 'livekit-client'; const room = new Room(); // Handle connection errors room.on(RoomEvent.Disconnected, (reason) => { console.error('Disconnected:', reason); }); // Handle device errors room.on(RoomEvent.MediaDevicesError, (error: Error) => { const failure = MediaDeviceFailure.getFailure(error); switch (failure) { case MediaDeviceFailure.PermissionDenied: console.error('Need to request permissions'); break; case MediaDeviceFailure.NotFound: console.error('Device not available'); break; case MediaDeviceFailure.DeviceInUse: console.error('Device in use by another app'); break; } }); // Connect with error handling try { await room.connect(serverUrl, token, { maxRetries: 3, }); await room.localParticipant.enableCameraAndMicrophone(); } catch (error) { if (error instanceof ConnectionError) { console.error('Connection error:', error.reason); } else if (error instanceof DeviceUnsupportedError) { console.error('Device error:', error.message); } else { console.error('Unknown error:', error); } } // Handle RPC errors try { const result = await room.localParticipant!.performRpc({ destinationIdentity: 'remote-id', method: 'test', payload: 'data', responseTimeout: 5000, }); } catch (error) { if (error instanceof RpcError) { console.error('RPC error:', error.errorCode, error.message); } else if (error instanceof Error) { console.error('RPC timeout or other error:', error.message); } } ``` -------------------------------- ### Server Implementation Example: Node.js Token Generation Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md A Node.js example using `@livekit/server-sdk` to generate access tokens for LiveKit. This endpoint can be used by the client-side `TokenSource.endpoint`. ```typescript import { AccessToken } from '@livekit/server-sdk'; app.post('/livekit-token', async (req, res) => { const { room, identity, name, metadata } = req.body; try { const at = new AccessToken( process.env.LIVEKIT_API_KEY, process.env.LIVEKIT_API_SECRET ); at.addGrant({ room, roomJoin: true, canPublish: true, canSubscribe: true, identity, metadata, }); const token = await at.toJwt(); res.json({ url: process.env.LIVEKIT_URL || 'ws://localhost:7800', token, }); } catch (error) { res.status(500).json({ error: error.message }); } }); ``` -------------------------------- ### Documentation File Structure Example Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/README.md Illustrates the standard structure of a documentation file within the LiveKit Client SDK JS project, including sections for title, description, imports, source paths, major sections, subsections, and specific items with code signatures, parameters, returns, and examples. ```markdown # [Title] Brief description of what this covers **Import:** Show how to import **Source:** File path in repository ## [Major Section] ### [Subsection] **Description** #### [Specific Item] ```typescript // Code signature ``` **Parameters Table** — parameter details **Returns** — return type and description **Throws** — possible errors **Example** — complete working code [Links to related sections] ``` -------------------------------- ### Full Custom Token Source Example Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md An example of a complete custom token source implementation that calls a backend API to generate tokens. It includes handling of various options and error checking for the fetch request. ```typescript import { TokenSource } from 'livekit-client'; const tokenSource = TokenSource.custom(async (options) => { const { roomName, participantName, participantIdentity, agentName, } = options; // Call your custom backend const response = await fetch('https://api.example.com/custom-token', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ room: roomName, identity: participantIdentity, name: participantName, agent: agentName, custom_data: { timestamp: Date.now() }, }), }); if (!response.ok) { throw new Error(`Token generation failed: ${response.status}`); } const data = await response.json(); return { serverUrl: data.serverUrl, participantToken: data.token, }; }); // Use with options const creds = await tokenSource.fetch({ roomName: 'chat-app', participantName: 'Bob', participantIdentity: 'bob-456', agentName: 'support-agent-1', }); ``` -------------------------------- ### Example: Using Video Presets Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Configure the Room with a default video resolution using a predefined `VideoPreset`. This ensures a consistent video quality for the room. ```typescript const room = new Room({ videoCaptureDefaults: { resolution: VideoPresets.h720.resolution, }, }); ``` -------------------------------- ### Handle Audio Playback Start Event Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/events-reference.md Listen for when an audio track's playback begins. No specific setup is required beyond having a track object. ```typescript track.on(TrackEvent.AudioPlaybackStarted, () => { console.log('Audio playback started'); }); ``` -------------------------------- ### Example: Connecting with Custom Headers via TokenSource Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md Demonstrates how to configure a `TokenSource` with custom headers, such as authorization, and then use it to connect to a LiveKit room. ```typescript import { TokenSource, Room } from 'livekit-client'; // Endpoint with custom headers const tokenSource = TokenSource.endpoint( 'https://api.example.com/livekit-token', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer api-key-123', 'X-Custom-Header': 'custom-value', }, } ); // Use for room connection const room = new Room(); const response = await tokenSource.fetch({ roomName: 'conference', participantName: 'John', participantIdentity: 'john-123', }); await room.connect(response.serverUrl, response.participantToken); ``` -------------------------------- ### Install LiveKit Client via NPM Source: https://github.com/livekit/client-sdk-js/blob/main/README.md Use this command to add the LiveKit client package to your project using NPM. ```shell npm install livekit-client --save ``` -------------------------------- ### Example: Set Volume to 50% Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/participant-api.md Sets the audio playback volume for a remote participant to 50% of the maximum. ```typescript remoteParticipant.setVolume(0.5); // 50% volume ``` -------------------------------- ### Connect to Room and Publish Media Source: https://github.com/livekit/client-sdk-js/blob/main/README.md This TypeScript example demonstrates initializing a room with adaptive streaming, setting up event listeners, and publishing local camera and microphone tracks. ```typescript import { LocalParticipant, LocalTrackPublication, Participant, RemoteParticipant, RemoteTrack, RemoteTrackPublication, Room, RoomEvent, Track, VideoPresets, } from 'livekit-client'; // creates a new room with options const room = new Room({ // automatically manage subscribed video quality adaptiveStream: true, // optimize publishing bandwidth and CPU for published tracks dynacast: true, // default capture settings videoCaptureDefaults: { resolution: VideoPresets.h720.resolution, }, }); // get your url from livekit's dashboard, or point it at a self hosted livekit deployment const url = "ws://localhost:7800"; // generate a token by making a request to a endpoint using the livekit server sdk or // using a prebuilt TokenSource (documented below) const token = "..."; // pre-warm connection, this can be called as early as your page is loaded room.prepareConnection(url, token); // set up event listeners room .on(RoomEvent.TrackSubscribed, handleTrackSubscribed) .on(RoomEvent.TrackUnsubscribed, handleTrackUnsubscribed) .on(RoomEvent.ActiveSpeakersChanged, handleActiveSpeakerChange) .on(RoomEvent.Disconnected, handleDisconnect) .on(RoomEvent.LocalTrackUnpublished, handleLocalTrackUnpublished); // connect to room await room.connect(url, token); console.log('connected to room', room.name); // publish local camera and mic tracks await room.localParticipant.enableCameraAndMicrophone(); function handleTrackSubscribed( track: RemoteTrack, publication: RemoteTrackPublication, participant: RemoteParticipant, ) { if (track.kind === Track.Kind.Video || track.kind === Track.Kind.Audio) { // attach it to a new HTMLVideoElement or HTMLAudioElement const element = track.attach(); parentElement.appendChild(element); } } function handleTrackUnsubscribed( track: RemoteTrack, publication: RemoteTrackPublication, participant: RemoteParticipant, ) { // remove tracks from all attached elements track.detach(); } function handleLocalTrackUnpublished( publication: LocalTrackPublication, participant: LocalParticipant, ) { // when local tracks are ended, update UI to remove them from rendering publication.track.detach(); } function handleActiveSpeakerChange(speakers: Participant[]) { // show UI indicators when participant is speaking } function handleDisconnect() { console.log('disconnected from room'); } ``` -------------------------------- ### Example: Static and Computed Token Sources Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md Demonstrates creating both static and dynamically computed token sources using TokenSource.literal and then fetching credentials to connect to a room. ```typescript import { TokenSource } from 'livekit-client'; // Static credentials const fixed1 = TokenSource.literal({ serverUrl: 'ws://localhost:7800', participantToken: 'token-string', }); // Computed credentials const fixed2 = TokenSource.literal(async () => { const response = await fetch('/api/credentials'); const data = await response.json(); return { serverUrl: data.url, participantToken: data.token, }; }); // Connect using token source const creds = await fixed1.fetch(); await room.connect(creds.serverUrl, creds.participantToken); ``` -------------------------------- ### Full Example: Connect to Room using Sandbox Token Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md Demonstrates a complete workflow of initializing the sandbox token source, fetching a token, and connecting to a LiveKit room. Ensure you replace the sandbox ID with your actual ID. ```typescript import { TokenSource, Room } from 'livekit-client'; const sandboxId = 'token-server-abcd1234efgh5678'; const tokenSource = TokenSource.sandboxTokenServer(sandboxId); const room = new Room(); try { const response = await tokenSource.fetch({ roomName: 'my-room', participantName: 'Alice', participantIdentity: 'alice-123', }); await room.connect(response.serverUrl, response.participantToken); } catch (error) { console.error('Failed to get token:', error); } ``` -------------------------------- ### Install LiveKit Client via Yarn Source: https://github.com/livekit/client-sdk-js/blob/main/README.md Use this command to add the LiveKit client package to your project using Yarn. ```shell yarn add livekit-client ``` -------------------------------- ### Project Directory Structure Example Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/README.md Provides an overview of the LiveKit Client SDK JS documentation's directory structure, highlighting key files and their purposes, such as INDEX.md for navigation and specific markdown files for core APIs, configuration, and advanced topics. ```markdown 📁 Reference Documentation ├── 📄 INDEX.md ← Start here for navigation ├── 📄 README.md ← This file │ ├─ Core APIs ├── 📄 room-api.md (Room class & connection) ├── 📄 participant-api.md (Participant management) ├── 📄 track-api.md (Media tracks) │ ├─ Configuration ├── 📄 types-reference.md (All TypeScript types) ├── 📄 configuration-reference.md (Configuration guide) ├── 📄 token-source-reference.md (Token generation) │ ├─ Advanced ├── 📄 events-reference.md (All events) ├── 📄 errors-reference.md (Error handling) ├── 📄 data-and-rpc-api.md (RPC & data) └── 📄 advanced-patterns.md (Best practices) ``` -------------------------------- ### Example: Creating and Attaching Local Tracks Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Demonstrates how to create local audio and video tracks with custom settings for echo cancellation, noise suppression, and video resolution. Attached video tracks are appended to the document body. ```typescript const tracks = await createLocalTracks({ audio: { echoCancellation: true, noiseSuppression: true, }, video: { resolution: { width: 1280, height: 720, }, facingMode: 'user', }, }); tracks.forEach(track => { if (track.kind === Track.Kind.Video) { const element = track.attach(); document.body.appendChild(element); } }); ``` -------------------------------- ### Example: Perform RPC Call Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/participant-api.md Demonstrates how to make an RPC call to a remote participant, including setting the destination, method, payload, and handling potential errors or timeouts. ```typescript try { const response = await room.localParticipant!.performRpc({ destinationIdentity: 'other-participant-id', method: 'calculate', payload: JSON.stringify({ operation: 'sum', a: 5, b: 3 }), responseTimeout: 5000, }); console.log('RPC response:', response); } catch (error) { console.error('RPC failed:', error); } ``` -------------------------------- ### Connect to LiveKit with Dynamic Token Sources Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md This example demonstrates how to connect to a LiveKit room using different token source strategies based on the environment. It covers development (sandbox), production (endpoint with credentials), and fallback (static tokens) scenarios. Ensure environment variables are set correctly for production and fallback methods. ```typescript import { Room, TokenSource } from 'livekit-client'; async function connectToLiveKit() { // Choose token source strategy based on environment let tokenSource; if (process.env.NODE_ENV === 'development') { // Development: Use sandbox tokenSource = TokenSource.sandboxTokenServer('token-server-abc123'); } else if (process.env.NEXT_PUBLIC_TOKEN_ENDPOINT) { // Production: Use endpoint with credentials tokenSource = TokenSource.endpoint( process.env.NEXT_PUBLIC_TOKEN_ENDPOINT, { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.API_KEY}`, }, } ); } else { // Fallback: Use static tokens tokenSource = TokenSource.literal({ serverUrl: process.env.NEXT_PUBLIC_LIVEKIT_URL!, participantToken: process.env.NEXT_PUBLIC_TOKEN!, }); } // Create room const room = new Room({ adaptiveStream: true, dynacast: true, }); try { // Get credentials from token source const credentials = await tokenSource.fetch({ roomName: 'my-app-room', participantName: getCurrentUserName(), participantIdentity: getCurrentUserId(), }); // Connect to room await room.connect( credentials.serverUrl, credentials.participantToken ); // Enable local media await room.localParticipant.enableCameraAndMicrophone(); console.log('Connected to LiveKit'); return room; } catch (error) { console.error('Failed to connect:', error); throw error; } } ``` -------------------------------- ### Handle Audio Playback Prompt Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Example demonstrating how to prompt the user to enable audio playback when it's not initially permitted. It listens for audio playback status changes and provides a button to initiate audio upon user interaction. ```typescript room.on(RoomEvent.AudioPlaybackStatusChanged, () => { if (!room.canPlaybackAudio) { button.onclick = () => { room.startAudio().then(() => { button.remove(); // Audio enabled, remove prompt }); }; } }); ``` -------------------------------- ### Subscribe to and Detach Media Tracks Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/INDEX.md This example shows how to attach incoming audio or video tracks to DOM elements for playback and how to detach them when no longer needed. ```typescript room.on(RoomEvent.TrackSubscribed, (track, publication, participant) => { const element = track.attach(); document.getElementById('video-container').appendChild(element); }); room.on(RoomEvent.TrackUnsubscribed, (track) => { track.detach(); }); ``` -------------------------------- ### Setup Comprehensive Error Handling for LiveKit Room Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/advanced-patterns.md Implement a central error handler for various room events like disconnections, media device issues, and track subscription failures. This setup ensures robust error management within your LiveKit application. ```typescript function setupErrorHandling(room: Room) { // Connection errors room.on(RoomEvent.Disconnected, (reason) => { handleDisconnect(reason); }); // Media device errors room.on(RoomEvent.MediaDevicesError, (error) => { const failure = MediaDeviceFailure.getFailure(error); switch (failure) { case MediaDeviceFailure.PermissionDenied: showError('Camera/microphone permission denied'); break; case MediaDeviceFailure.NotFound: showError('Camera or microphone not found'); break; case MediaDeviceFailure.DeviceInUse: showError('Device is in use by another application'); break; } }); // Track subscription errors room.on(RoomEvent.TrackSubscriptionFailed, (trackSid, participant, reason) => { console.error(`Failed to subscribe to ${trackSid}:`, reason); }); } ``` -------------------------------- ### Implement Selective Subscription Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/advanced-patterns.md Subscribe only to necessary tracks to manage bandwidth and resources. This example skips screen share tracks and only subscribes to primary video. ```typescript room.on(RoomEvent.TrackPublished, (publication, participant) => { // Only subscribe to camera video, skip screen shares if (publication.source === Track.Source.ScreenShare) { publication.setSubscribed(false); return; } // Only subscribe to primary video if (publication.kind === Track.Kind.Video) { publication.setSubscribed(true); } }); ``` -------------------------------- ### Get Server Information Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Access information about the LiveKit server. This property provides details about the server hosting the room. ```typescript get serverInfo(): Partial | undefined ``` -------------------------------- ### Example: Unsubscribe from Camera Track Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/participant-api.md Demonstrates how to find a remote participant's camera track and then unsubscribe from it using its track SID. ```typescript const cameraTrack = remoteParticipant.getTrackPublication(Track.Source.Camera); if (cameraTrack) { remoteParticipant.setTrackSubscribed(cameraTrack.trackSid!, false); console.log('Unsubscribed from camera'); } ``` -------------------------------- ### Handle Video Playback Start Event Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/events-reference.md Subscribe to notifications when video track playback commences. This event requires no special arguments. ```typescript track.on(TrackEvent.VideoPlaybackStarted, () => { console.log('Video playback started'); }); ``` -------------------------------- ### Endpoint Token Source Fetch Example Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md Demonstrates fetching tokens from an endpoint and illustrates caching behavior. Caching occurs when subsequent fetch requests use identical options. ```typescript const tokenSource = TokenSource.endpoint('https://example.com/token'); // Request 1 - fetches from endpoint const response1 = await tokenSource.fetch({ roomName: 'room-a', participantName: 'Alice', }); // Request 2 - same options, returns cached response const response2 = await tokenSource.fetch({ roomName: 'room-a', participantName: 'Alice', }); // Request 3 - different options, fetches from endpoint const response3 = await tokenSource.fetch({ roomName: 'room-b', participantName: 'Bob', }); ``` -------------------------------- ### Example RPC Call Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/data-and-rpc-api.md Demonstrates a simple RPC call to a remote participant. Includes basic try-catch block for handling potential RpcError or network errors. ```typescript // Simple RPC call try { const response = await room.localParticipant!.performRpc({ destinationIdentity: 'alice-123', method: 'greet', payload: 'Hello from Bob!', responseTimeout: 5000, }); console.log('Response:', response); } catch (error) { if (error instanceof RpcError) { console.error(`RPC error: ${error.errorCode} - ${error.message}`); } else { console.error('RPC call failed:', error); } } ``` -------------------------------- ### Start Audio Playback Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Initiate audio playback for the room. This method must be called within a user interaction handler (e.g., a click or tap event) due to browser autoplay policies. ```typescript async startAudio(): Promise ``` -------------------------------- ### List Local Media Devices Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Use this method to get a list of available audio and video input/output devices. You can filter the results by specifying the device kind. ```typescript static async getLocalDevices(kind?: MediaDeviceKind): Promise ``` ```typescript // List all cameras const cameras = await Room.getLocalDevices('videoinput'); cameras.forEach(device => console.log(device.label)); ``` -------------------------------- ### Implement Custom Log Extension Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/configuration-reference.md Extend the SDK's logging mechanism to send logs to an external service. This example shows how to capture log level, message, and context for processing. ```typescript import { setLogExtension, LogLevel } from 'livekit-client'; setLogExtension((level, msg, context) => { const timestamp = new Date().toISOString(); const levelName = LogLevel[level]; // Send to external logging service fetch('/api/logs', { method: 'POST', body: JSON.stringify({ timestamp, level: levelName, message: msg, context, }), }).catch(err => console.error('Failed to send log:', err)); }); ``` -------------------------------- ### RemoteVideoTrack.requestedQuality Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Gets the currently requested quality tier for the remote video track. ```APIDOC ## RemoteVideoTrack.requestedQuality ### Description Requested quality tier. ### Properties #### requestedQuality?: VideoQuality ``` -------------------------------- ### Instantiate Room with Options Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Create a new Room instance, configuring adaptive streaming, dynamic casting, video capture resolution, and audio output device. ```typescript import { Room, VideoPresets } from 'livekit-client'; const room = new Room({ adaptiveStream: true, dynacast: true, videoCaptureDefaults: { resolution: VideoPresets.h720.resolution, }, audioOutput: { deviceId: 'preferred-device-id', }, }); ``` -------------------------------- ### RemoteVideoTrack.dimensions Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Gets the current video dimensions (width and height in pixels) of the remote video track. ```APIDOC ## RemoteVideoTrack.dimensions ### Description Current video dimensions. ### Properties #### dimensions?: VideoResolution - **width** (number) - Width in pixels - **height** (number) - Height in pixels ``` -------------------------------- ### Get Synchronization Source ID Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Retrieves the RTP synchronization source (SSRC) ID for the track. ```typescript getSynchronizationSource(): number | undefined ``` -------------------------------- ### Get Room Name Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Access the name of the room. This property provides the identifier for the current room. ```typescript get name(): string ``` -------------------------------- ### Get Requested Video Quality Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Retrieves the currently requested quality tier for a remote video track. ```typescript get requestedQuality(): VideoQuality | undefined ``` -------------------------------- ### Get isLocal property Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md This property is always true for local tracks, indicating that the track originates from the current participant. ```typescript get isLocal(): true ``` -------------------------------- ### connect() Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Establishes a connection to the LiveKit server and joins a specified room. It handles WebSocket URL, authentication token, and optional connection configurations. ```APIDOC ## connect() ### Description Establishes connection to LiveKit server and joins a room. ### Method `async connect(url: string, token: string, options?: RoomConnectOptions): Promise` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **url** (`string`) - Required - WebSocket URL of LiveKit server (e.g., `ws://localhost:7800`) - **token** (`string`) - Required - Access token with room and participant info - **options** (`RoomConnectOptions`) - Optional - Connection configuration **Connection Options:** - **autoSubscribe** (`boolean`) - Optional - Default: `true` - Automatically subscribe to published tracks - **peerConnectionTimeout** (`number`) - Optional - Default: `15000` - Milliseconds to wait for PeerConnection establishment - **maxRetries** (`number`) - Optional - Default: `3` - Number of retry attempts for initial join - **websocketTimeout** (`number`) - Optional - Default: `15000` - Milliseconds to wait for WebSocket connection - **rtcConfig** (`RTCConfiguration`) - Optional - Custom WebRTC configuration ### Throws - **ConnectionError**: Failed to establish connection to server - **UnsupportedServer**: Server version incompatible with SDK - **UnexpectedConnectionState**: Room already connected or connecting ### Request Example ```typescript try { await room.connect('ws://localhost:7800', token, { autoSubscribe: true, peerConnectionTimeout: 15000, }); console.log('Connected to room:', room.name); } catch (error) { console.error('Failed to connect:', error); } ``` ### Response #### Success Response (200) * None (Promise resolves on successful connection) #### Response Example * None ``` -------------------------------- ### Get and Attach Camera Track Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/participant-api.md Retrieve the camera track publication for a participant and attach it to a video element if subscribed. ```typescript const cameraTrack = participant.getTrackPublication(Track.Source.Camera); if (cameraTrack && cameraTrack.isSubscribed) { const videoElement = cameraTrack.videoTrack?.attach(); } ``` -------------------------------- ### Create Local Tracks with Options Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Create audio and video tracks with specific capture configurations. This is useful for setting up tracks before joining a room. Ensure necessary permissions are granted and devices are supported. ```typescript async createLocalTracks(options?: CreateLocalTracksOptions): Promise ``` -------------------------------- ### RoomEvent.Connected Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/events-reference.md Emitted when the client has successfully connected to the LiveKit room. This is a good point to start publishing or subscribing to tracks. ```APIDOC ## RoomEvent.Connected Emitted when successfully connected to room. ```typescript room.on(RoomEvent.Connected, () => { console.log('Connected to room:', room.name); // Ready to publish/subscribe }); ``` ``` -------------------------------- ### Get Remote Video Track Dimensions Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Retrieves the current resolution (width and height in pixels) of a remote video track. ```typescript get dimensions(): VideoResolution | undefined ``` -------------------------------- ### Configure TokenSource.SandboxTokenServer Source: https://github.com/livekit/client-sdk-js/blob/main/README.md Use this for prototyping with LiveKit-hosted token generation. Do not use this in production environments. ```ts const sandbox = TokenSource.sandboxTokenServer("token-server-xxxxxx"); await sandbox.fetch({ agentName: "agent to dispatch" }); // { serverUrl: "...", participantToken: "... token encoding agentName ..." } ``` -------------------------------- ### Get Encoding Parameters for LocalVideoTrack Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Retrieve the WebRTC encoding configuration for simulcast or layers applied to a local video track. ```typescript get encodingParameters(): RTCRtpEncodingParameters[] | undefined ``` -------------------------------- ### startAudio() Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Begins audio playback. This method must be called within a user interaction handler (e.g., a click or tap event) to comply with browser autoplay policies. ```APIDOC ## startAudio() ### Description Begin audio playback. Must be called within user interaction handler (click/tap). ### Method ```typescript async startAudio(): Promise ``` ### Throws - Error: Called outside user interaction context ### Example ```typescript room.on(RoomEvent.AudioPlaybackStatusChanged, () => { if (!room.canPlaybackAudio) { button.onclick = () => { room.startAudio().then(() => { button.remove(); // Audio enabled, remove prompt }); }; } }); ``` ``` -------------------------------- ### Initialize and Connect with CommonJS Source: https://github.com/livekit/client-sdk-js/blob/main/README.md Use this pattern for CommonJS environments. The prepareConnection method can be used to optimize connection latency. ```javascript const livekit = require('livekit-client'); const room = new livekit.Room(...); // call this some time before actually connecting to speed up the actual connection room.prepareConnection(url, token); await room.connect(...); ``` -------------------------------- ### Get Remote Participant Audio Volume Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/participant-api.md Retrieves the current playback volume setting for a remote participant's audio stream. ```typescript getVolume(): number ``` -------------------------------- ### Get Last Camera Error Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/participant-api.md Retrieve the last error encountered during camera capture. This property is useful for debugging camera-related issues. ```typescript get lastCameraError(): Error | undefined ``` -------------------------------- ### Custom Token Source with Fetch Options Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/token-source-reference.md Demonstrates how to create a custom token source and fetch credentials with custom parameters. The callback function should implement custom credential generation logic. ```typescript const tokenSource = TokenSource.custom(async (options) => { // Implement your own credential generation logic const credentials = await generateCredentialsWithCustomLogic(options); return { serverUrl: credentials.url, participantToken: credentials.token, }; }); // Fetch with parameters const response = await tokenSource.fetch({ custom_field_1: 'value1', custom_field_2: 'value2', }); ``` -------------------------------- ### Get Last Microphone Error Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/participant-api.md Retrieve the last error encountered during microphone capture. This property is useful for debugging microphone-related issues. ```typescript get lastMicrophoneError(): Error | undefined ``` -------------------------------- ### prepareConnection() Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Pre-warms the WebRTC connection without fully joining the room, which can reduce the actual connection time when `connect()` is called later. ```APIDOC ## prepareConnection() ### Description Pre-warm WebRTC connection without fully joining. Useful for reducing actual connection time. ### Method `async prepareConnection(url: string, token: string): Promise` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **url** (`string`) - Required - WebSocket URL of LiveKit server - **token** (`string`) - Required - Access token ### Response #### Success Response (200) * None (Promise resolves when connection is prepared) #### Response Example * None ### Example ```typescript // Call early in page load to prepare connection room.prepareConnection(url, token); // Later, actual connection is faster await room.connect(url, token); ``` ``` -------------------------------- ### createLocalTracks() Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/track-api.md Creates audio and/or video tracks locally without needing to join a room first. This is useful for previewing tracks or preparing them before a connection is established. ```APIDOC ## createLocalTracks() ### Description Creates audio and/or video tracks locally without needing to join a room first. This is useful for previewing tracks or preparing them before a connection is established. ### Method `async createLocalTracks(options?: CreateLocalTracksOptions): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body ##### options (`CreateLocalTracksOptions`) - **audio** (`boolean | AudioCaptureOptions`) - Optional - Audio capture settings - **video** (`boolean | VideoCaptureOptions`) - Optional - Video capture settings - **screenShare** (`ScreenShareCaptureOptions`) - Optional - Screen share settings ### Request Example ```typescript const tracks = await createLocalTracks({ audio: { echoCancellation: true, noiseSuppression: true, }, video: { resolution: { width: 1280, height: 720, }, facingMode: 'user', }, }); tracks.forEach(track => { if (track.kind === Track.Kind.Video) { const element = track.attach(); document.body.appendChild(element); } }); ``` ### Response #### Success Response (200) - **LocalTrack[]** - Array of created LocalTrack instances #### Response Example (See Request Example for track usage) ### Throws - **Error** - Permissions denied - **DeviceUnsupportedError** - Required device not available ``` -------------------------------- ### Get and Write to Text Stream Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/data-and-rpc-api.md Obtain a text stream writer for a given topic and write data to it. Ensure to close the stream when done. ```typescript // Get text stream writer const writer = await room.localParticipant!.createTextStreamWriter({ topic: 'events', }); // Write data await writer.write('event: user-joined'); await writer.write('event: user-left'); // Close stream await writer.close(); ``` -------------------------------- ### Get Room Metadata Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Retrieve metadata associated with the room, as set by the server. This can contain custom information about the room's configuration or state. ```typescript get metadata(): string ``` -------------------------------- ### Room Constructor Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Creates a new Room instance with optional configuration. ```APIDOC ## Room Constructor ### Description Creates a new Room instance with optional configuration. ### Signature ```typescript constructor(options?: RoomOptions) ``` ### Parameters #### Path Parameters - **options** (`RoomOptions`) - Optional - Configuration for room behavior and defaults ### RoomOptions | Option | Type | Required | Default | Description | |---|---|---|---|---| | adaptiveStream | `AdaptiveStreamSettings | boolean` | No | true | Automatically manage quality of subscribed video to optimize bandwidth and CPU | | dynacast | `boolean` | No | true | Enable dynamic layer pause for simulcast/SVC video | | audioCaptureDefaults | `AudioCaptureOptions` | No | — | Default settings for audio capture | | videoCaptureDefaults | `VideoCaptureOptions` | No | — | Default settings for video capture | | publishDefaults | `TrackPublishDefaults` | No | — | Default settings for track publishing | | audioOutput | `AudioOutputOptions` | No | — | Audio output configuration | | stopLocalTrackOnUnpublish | `boolean` | No | true | Stop local tracks when unpublished | | reconnectPolicy | `ReconnectPolicy` | No | DefaultReconnectPolicy | Policy for handling reconnection attempts | | disconnectOnPageLeave | `boolean` | No | true | Automatically disconnect when page unloads | | webAudioMix | `boolean | WebAudioSettings` | No | false | Mix audio tracks in Web Audio API | | encryption | `E2EEOptions` | No | — | End-to-end encryption configuration | | frameMetadata | `FrameMetadataOptions` | No | — | Frame-level metadata options for video tracks | | singlePeerConnection | `boolean` | No | true | Use single peer connection mode | ### Example ```typescript import { Room, VideoPresets } from 'livekit-client'; const room = new Room({ adaptiveStream: true, dynacast: true, videoCaptureDefaults: { resolution: VideoPresets.h720.resolution, }, audioOutput: { deviceId: 'preferred-device-id', }, }); ``` ``` -------------------------------- ### Manage CPU and Bandwidth Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/advanced-patterns.md Optimize CPU and bandwidth by using VP9 with temporal layers for better efficiency. Monitor and adjust based on CPU usage by listening to RoomEvent.TrackPublished. ```typescript const room = new Room({ publishDefaults: { // Use VP9 with temporal layers for better efficiency videoCodec: 'vp9', videoEncoding: { maxBitrate: 2500000, maxFramerate: 30, numTemporalLayers: 3, // 3-layer simulcast }, }, }); // Monitor and adjust based on CPU usage room.on(RoomEvent.TrackPublished, (publication, participant) => { // Can monitor CPU via WebRTC stats }); ``` -------------------------------- ### Complete LiveKit Room Configuration Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/configuration-reference.md Set up a LiveKit room with comprehensive options including adaptive streaming, capture defaults, publishing settings, and connection policies. Event listeners are also configured. ```typescript import { Room, VideoPresets, ConnectionState, RoomEvent, logLevel, } from 'livekit-client'; // Configure logging setLogLevel(LogLevel.debug); // Create room with full configuration const room = new Room({ // Adaptive quality adaptiveStream: { pixelsPerFrame: 86400, pauseVideoResolution: VideoPresets.h180.resolution, pauseVideoFramerate: 2, }, dynacast: true, // Capture defaults videoCaptureDefaults: { resolution: VideoPresets.h720.resolution, frameRate: 30, }, audioCaptureDefaults: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, // Publishing publishDefaults: { videoCodec: 'vp9', videoEncoding: { maxBitrate: 2500000, maxFramerate: 30, }, simulcast: true, }, // Audio output audioOutput: { deviceId: undefined, // Use default }, // Behavior stopLocalTrackOnUnpublish: true, disconnectOnPageLeave: true, singlePeerConnection: true, // Web audio mixing for autoplay webAudioMix: true, // Connection reconnectPolicy: new DefaultReconnectPolicy(5000, 30000, 3), }); // Set up event listeners room.on(RoomEvent.Connected, () => { console.log('Room connected'); }); room.on(RoomEvent.ConnectionStateChanged, (state) => { console.log('Connection state:', state); }); // Connect with options await room.connect(serverUrl, participantToken, { autoSubscribe: true, peerConnectionTimeout: 15000, maxRetries: 3, rtcConfig: { iceServers: [ { urls: ['stun:stun1.l.google.com:19302'] }, ], }, }); // Publish local media await room.localParticipant.enableCameraAndMicrophone(); ``` -------------------------------- ### Integrate Virtual Background Track Processor Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/advanced-patterns.md Sets up and configures a virtual background using a track processor. Requires importing VirtualBackgroundProcessor and initializing it. ```typescript import { VirtualBackgroundProcessor } from '@livekit/components-core'; async function setupVirtualBackground(room: Room) { const videoTrack = room.localParticipant .videoTrackPublications.values().next().value?.videoTrack; if (!videoTrack) return; const processor = new VirtualBackgroundProcessor(); await processor.init(); await videoTrack.addProcessor(processor); // Configure background await processor.setBackground({ type: 'color', color: '#0000FF', }); // Remove when done // await videoTrack.removeProcessor(processor); } ``` -------------------------------- ### Get Remote Participants Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Retrieve a map of all remote participants in the room, keyed by their identity. This allows for easy access to information about other users connected to the room. ```typescript get remoteParticipants(): Map ``` -------------------------------- ### Get Room Connection State Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Retrieve the current connection state of the room. This is useful for understanding the room's status and handling connection-related events. ```typescript get state(): ConnectionState ``` -------------------------------- ### Manage Local Media Devices Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/INDEX.md List available media input devices like cameras and microphones, and switch to a different camera if multiple are present. ```typescript // List cameras const cameras = await Room.getLocalDevices('videoinput'); // Switch to different camera const deviceId = cameras[1].deviceId; await room.switchActiveDevice('videoinput', deviceId); ``` -------------------------------- ### RoomOptions Interface Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/types-reference.md Options for initializing a new `Room` instance. Configure adaptive streaming, publishing defaults, and other room-level settings. ```typescript interface RoomOptions { adaptiveStream?: AdaptiveStreamSettings | boolean; dynacast?: boolean; audioCaptureDefaults?: AudioCaptureOptions; videoCaptureDefaults?: VideoCaptureOptions; publishDefaults?: TrackPublishDefaults; audioOutput?: AudioOutputOptions; stopLocalTrackOnUnpublish?: boolean; reconnectPolicy?: ReconnectPolicy; disconnectOnPageLeave?: boolean; webAudioMix?: boolean | WebAudioSettings; encryption?: E2EEOptions; frameMetadata?: FrameMetadataOptions; singlePeerConnection?: boolean; } ``` -------------------------------- ### Get Web Audio Context Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Retrieve the WebAudioAPI AudioContext if web audio mixing is enabled. This is useful for advanced audio processing or custom audio routing. ```typescript getAudioContext(): AudioContext ``` -------------------------------- ### List and Select Media Devices Source: https://github.com/livekit/client-sdk-js/blob/main/README.md Enumerate available input devices and switch the active device for the current room. ```typescript // list all microphone devices const devices = await Room.getLocalDevices('audioinput'); // select last device const device = devices[devices.length - 1]; // in the current room, switch to the selected device and set // it as default audioinput in the future. await room.switchActiveDevice('audioinput', device.deviceId); ``` -------------------------------- ### Get Active Speakers Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/room-api.md Obtain an array of participants who are currently speaking, ordered by their audio level. This is useful for features like highlighting active speakers in a UI. ```typescript get activeSpeakers(): Participant[] ``` -------------------------------- ### Configure Basic Room Settings Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/configuration-reference.md Customize room behavior with options like adaptive streaming, dynamic codec selection, default capture settings, and publishing defaults. Also configures client-side behavior like stopping local tracks on unpublish and disconnecting on page leave. ```typescript import { Room, VideoPresets } from 'livekit-client'; const room = new Room({ // Automatic quality management adaptiveStream: true, dynacast: true, // Default capture settings videoCaptureDefaults: { resolution: VideoPresets.h720.resolution, frameRate: 30, }, audioCaptureDefaults: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, }, // Publishing defaults publishDefaults: { videoCodec: 'vp9', dtx: true, }, // Behavior stopLocalTrackOnUnpublish: true, disconnectOnPageLeave: true, singlePeerConnection: true, }); ``` -------------------------------- ### TranscriptionSegment Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/types-reference.md Represents a segment of transcribed speech. It includes the text, start and end times, a flag indicating if it's final, and optional language and participant identity. ```APIDOC ## TranscriptionSegment ### Description Represents a segment of transcribed speech. It includes the text, start and end times, a flag indicating if it's final, and optional language and participant identity. ### Type Definition ```typescript interface TranscriptionSegment { id: string; text: string; startTime: number; endTime: number; final: boolean; language?: string; participantIdentity?: string; } ``` ``` -------------------------------- ### Log Participant Speaking State Changes Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/events-reference.md Use this snippet to log when a participant starts or stops speaking. It requires the `ParticipantEvent.IsSpeakingChanged` event and checks the `isSpeaking` boolean. ```typescript participant.on(ParticipantEvent.IsSpeakingChanged, (isSpeaking) => { if (isSpeaking) { console.log(`${participant.name} started speaking`); } else { console.log(`${participant.name} stopped speaking`); } }); ``` -------------------------------- ### Configure Room for Best Quality Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/INDEX.md Use this configuration for the best video and audio quality. It sets higher resolutions and bitrates. ```typescript const room = new Room({ adaptiveStream: true, dynacast: true, videoCaptureDefaults: { resolution: VideoPresets.h1080.resolution, }, publishDefaults: { videoCodec: 'vp9', videoEncoding: { maxBitrate: 2500000, maxFramerate: 30, }, }, }); ``` -------------------------------- ### Handle Room Connected Event Source: https://github.com/livekit/client-sdk-js/blob/main/_autodocs/events-reference.md Listen for the RoomEvent.Connected event to know when the client has successfully connected to the room. This is a good point to start publishing or subscribing to tracks. ```typescript room.on(RoomEvent.Connected, () => { console.log('Connected to room:', room.name); // Ready to publish/subscribe }); ```