### Run the Example Source: https://github.com/livekit/node-sdks/blob/main/examples/data-streams/README.md Execute this command to start the DataStreams example. ```bash pnpm run start ``` -------------------------------- ### Install Dependencies Source: https://github.com/livekit/node-sdks/blob/main/examples/data-streams/README.md Run this command to install the necessary dependencies for the example. ```bash pnpm install ``` -------------------------------- ### Install livekit-server-sdk Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Install the SDK using your preferred package manager. ```bash pnpm add livekit-server-sdk ``` ```bash yarn add livekit-server-sdk ``` ```bash npm install livekit-server-sdk --save ``` -------------------------------- ### Build All Packages in Monorepo with pnpm Source: https://github.com/livekit/node-sdks/blob/main/README.md Build all packages within the monorepo, including those in `/packages` and `/examples`. This is useful for initial setup and verifying installations. ```shell pnpm build ``` -------------------------------- ### Install Git Submodules Source: https://github.com/livekit/node-sdks/blob/main/README.md Run this command to install submodules. Ensure you run `pnpm build` afterwards. ```shell git submodule update --init --recursive ``` -------------------------------- ### Start Room Composite Egress Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Demonstrates how to start a Room Composite Egress using the updated v2 syntax. It shows the instantiation of `EncodedFileOutput` with an explicit `case` for the output type (e.g., 's3'). ```APIDOC ## startRoomCompositeEgress ### Description Starts a Room Composite Egress, which captures the entire room view as a composite stream. ### Method `egressClient.startRoomCompositeEgress(roomName, egressOptions)` ### Parameters #### Path Parameters - **roomName** (string) - Required - The name of the room to egress. #### Request Body - **egressOptions** (object) - Required - Options for the egress request. - **file** (EncodedFileOutput) - Required - Configuration for file output. - **filepath** (string) - Required - The desired path for the output file. - **output** (object) - Required - Specifies the output destination and format. - **case** (string) - Required - The type of output (e.g., 's3', 'gcs', 'azure'). - **value** (object) - Required - The specific configuration for the chosen output type. - **s3** (S3Upload) - Configuration for S3 upload. - **accessKey** (string) - Required - AWS access key. - **secret** (string) - Required - AWS secret key. - **bucket** (string) - Required - S3 bucket name. - **gcs** (GCSUpload) - Configuration for GCS upload. - **azure** (AzureUpload) - Configuration for Azure upload. ### Request Example ```typescript const fileOutput = new EncodedFileOutput({ filepath: 'dz/davids-room-test.mp4', output: { case: 's3', value: new S3Upload({ accessKey: 'aws-access-key', secret: 'aws-access-secret', bucket: 'my-bucket', }), }, }); const info = await egressClient.startRoomCompositeEgress('my-room', { file: fileOutput, }); ``` ### Response #### Success Response (200) - **info** (object) - Information about the started egress process. ``` -------------------------------- ### Example of Received Webhook Event Log Source: https://github.com/livekit/node-sdks/blob/main/examples/webhooks-nextjs/README.md Observe the structure of a received webhook event in your Next.js application logs. This example shows a participant_joined event. ```text received webhook event { event: 'participant_joined', ... } ``` -------------------------------- ### Start Room Composite Egress (v2) Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Use this snippet to start a Room Composite Egress with updated v2 syntax. Note the use of classes and the explicit 'case' field for the output type. ```typescript const fileOutput = new EncodedFileOutput({ filepath: 'dz/davids-room-test.mp4', output: { case: 's3', value: new S3Upload({ accessKey: 'aws-access-key', secret: 'aws-access-secret', bucket: 'my-bucket', }), }, }); const info = await egressClient.startRoomCompositeEgress('my-room', { file: fileOutput, }); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/livekit/node-sdks/blob/main/examples/data-streams/README.md Create a .env.local file and populate it with your LiveKit credentials and URL. ```bash LIVEKIT_API_KEY=your_api_key LIVEKIT_API_SECRET=your_api_secret LIVEKIT_URL=your_livekit_url ``` -------------------------------- ### Publish an Audio Track Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-rtc/README.md Publishes an audio track to the connected room. It demonstrates setting up an audio source, creating a local audio track, and capturing audio frames. Note the recommendation to use `buffer.subarray` over `buffer.slice` for converting Uint8Array to Int16Array to avoid potential issues. ```typescript import { AudioFrame, AudioSource, LocalAudioTrack, TrackPublishOptions, TrackSource, } from '@livekit/rtc-node'; import { readFileSync } from 'node:fs'; // set up audio track const source = new AudioSource(16000, 1); const track = LocalAudioTrack.createAudioTrack('audio', source); const options = new TrackPublishOptions(); options.source = TrackSource.SOURCE_MICROPHONE; // note: if converting from Uint8Array to Int16Array, *do not* use buffer.slice! // it is marked unstable by Node and can cause undefined behaviour, such as massive chunks of // noise being added to the end. // it is recommended to use buffer.subarray instead. const sample = readFileSync(pathToFile); var buffer = new Int16Array(sample.buffer); await room.localParticipant.publishTrack(track, options); await source.captureFrame(new AudioFrame(buffer, 16000, 1, buffer.byteLength / 2)); // cleanup resources await track.close(); ``` -------------------------------- ### Creating Access Tokens Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Generate access tokens for participants to join LiveKit rooms. Tokens can be configured with specific permissions and have an optional expiration time. ```APIDOC ## AccessToken ### Description Creates an access token for a participant to join a LiveKit room. The token can be configured with various grants and an optional Time-To-Live (TTL). ### Method `new AccessToken(apiKey: string, apiSecret: string, options?: { identity: string, ttl?: number | string })` ### Method `addGrant(grant: { roomJoin: boolean, room: string, canPublish?: boolean, canSubscribe?: boolean })` ### Method `toJwt(): Promise` ### Example ```typescript import { AccessToken } from 'livekit-server-sdk'; const roomName = 'name-of-room'; const participantName = 'user-name'; const at = new AccessToken('api-key', 'secret-key', { identity: participantName, }); at.addGrant({ roomJoin: true, room: roomName }); const token = await at.toJwt(); console.log('access token', token); ``` ### Example with Permissions ```typescript const at = new AccessToken('api-key', 'secret-key', { identity: participantName, }); at.addGrant({ roomJoin: true, room: roomName, canPublish: false, canSubscribe: true, }); ``` ``` -------------------------------- ### Managing Rooms Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Use the `RoomServiceClient` to perform administrative operations on LiveKit rooms, such as listing, creating, and deleting them. ```APIDOC ## RoomServiceClient ### Description Provides APIs to manage LiveKit rooms. Requires API key and secret key for authentication. ### Constructor `new RoomServiceClient(livekitHost: string, apiKey: string, apiSecret: string)` ### Method `listRooms(): Promise` ### Description Retrieves a list of all active rooms in the LiveKit deployment. ### Method `createRoom(options: { name: string, emptyTimeout?: number, maxParticipants?: number }): Promise` ### Description Creates a new LiveKit room with specified options. ### Method `deleteRoom(roomName: string): Promise` ### Description Deletes a LiveKit room by its name. ### Example ```typescript import { Room, RoomServiceClient } from 'livekit-server-sdk'; const livekitHost = 'https://my.livekit.host'; const svc = new RoomServiceClient(livekitHost, 'api-key', 'secret-key'); // list rooms svc.listRooms().then((rooms: Room[]) => { console.log('existing rooms', rooms); }); // create a new room const opts = { name: 'myroom', emptyTimeout: 10 * 60, // 10 minutes maxParticipants: 20, }; sdc.createRoom(opts).then((room: Room) => { console.log('room created', room); }); // delete a room svc.deleteRoom('myroom').then(() => { console.log('room deleted'); }); ``` ``` -------------------------------- ### Connect to a LiveKit Room Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-rtc/README.md Connects to a LiveKit room and sets up event listeners for track subscriptions, disconnections, and local track publications. Ensure to disconnect and dispose of resources when the application exits. ```typescript import { RemoteParticipant, RemoteTrack, RemoteTrackPublication, Room, RoomEvent, dispose, } from '@livekit/rtc-node'; const room = new Room(); await room.connect(url, token, { autoSubscribe: true, dynacast: true }); console.log('connected to room', room); // add event listeners room .on(RoomEvent.TrackSubscribed, handleTrackSubscribed) .on(RoomEvent.Disconnected, handleDisconnected) .on(RoomEvent.LocalTrackPublished, handleLocalTrackPublished); process.on('SIGINT', () => { await room.disconnect(); await dispose(); }); ``` -------------------------------- ### Create Access Token for Room Join Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Generate an access token for a participant to join a specified room. The room will be created automatically if it doesn't exist when the first client joins. The token can be configured with custom permissions. ```typescript import { AccessToken } from 'livekit-server-sdk'; // if this room doesn't exist, it'll be automatically created when the first // client joins const roomName = 'name-of-room'; // identifier to be used for participant. // it's available as LocalParticipant.identity with livekit-client SDK const participantName = 'user-name'; const at = new AccessToken('api-key', 'secret-key', { identity: participantName, }); at.addGrant({ roomJoin: true, room: roomName }); const token = await at.toJwt(); console.log('access token', token); ``` ```typescript const at = new AccessToken('api-key', 'secret-key', { identity: participantName, }); at.addGrant({ roomJoin: true, room: roomName, canPublish: false, canSubscribe: true, }); ``` -------------------------------- ### Manage LiveKit Rooms Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Use RoomServiceClient to perform operations on rooms, such as listing, creating, and deleting them. Requires API key and secret for authentication. ```typescript import { Room, RoomServiceClient } from 'livekit-server-sdk'; const livekitHost = 'https://my.livekit.host'; const svc = new RoomServiceClient(livekitHost, 'api-key', 'secret-key'); // list rooms svc.listRooms().then((rooms: Room[]) => { console.log('existing rooms', rooms); }); // create a new room const opts = { name: 'myroom', // timeout in seconds emptyTimeout: 10 * 60, maxParticipants: 20, }; sdc.createRoom(opts).then((room: Room) => { console.log('room created', room); }); // delete a room svc.deleteRoom('myroom').then(() => { console.log('room deleted'); }); ``` -------------------------------- ### LiveKit Server Webhook Configuration Source: https://github.com/livekit/node-sdks/blob/main/examples/webhooks-http/README.md Configure your LiveKit server to send webhook events to your application. Ensure the webhook URL is accessible and provide an API key for authentication. ```yaml webhook: urls: - http://localhost:3000/ api_key: ``` -------------------------------- ### Set Environment Variables for API Key and Secret Source: https://github.com/livekit/node-sdks/blob/main/examples/webhooks-nextjs/README.md Store your LiveKit API key and secret in environment variables for secure access within your Next.js application. This is typically done in a .env.local file. ```env LIVEKIT_API_KEY=your-api-key LIVEKIT_API_SECRET=your-api-secret ``` -------------------------------- ### Migrate Token Generation to v2 Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Update token generation and verification methods to use the asynchronous APIs introduced in v2, which replaced the `jsonwebtoken` library with `jose`. ```typescript const at = new AccessToken('api-key', 'secret-key', { identity: participantName, }); at.addGrant({ roomJoin: true, room: roomName }); // v1 // const token = at.toJWT(); // v2 const token = await at.toJwt(); ``` ```typescript // v1 // const grants = v.verify(token); // v2 const grants = await v.verify(token); ``` ```typescript app.post('/webhook-endpoint', async (req, res) => { // v1 // const event = receiver.receive(req.body, req.get('Authorization')); // v2 const event = await receiver.receive(req.body, req.get('Authorization')); }); ``` -------------------------------- ### Register an RPC Method Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-rtc/README.md Registers a method on the local participant to be callable by other participants in the room. The handler receives invocation data and can return a response or throw an `RpcError`. ```typescript room.localParticipant?.registerRpcMethod( // method name - can be any string that makes sense for your application 'greet', // method handler - will be called when the method is invoked by a RemoteParticipant async (data: RpcInvocationData) => { console.log(`Received greeting from ${data.callerIdentity}: ${data.payload}`); return `Hello, ${data.callerIdentity}!`; } ); ``` -------------------------------- ### Perform an RPC Request Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-rtc/README.md Initiates an RPC call to a specified participant and method with a given payload. Handles potential errors during the call and logs the response. Consider adjusting `responseTimeout` for optimal performance. ```typescript try { const response = await room.localParticipant!.performRpc({ destinationIdentity: 'recipient-identity', method: 'greet', payload: 'Hello from RPC!', }); console.log('RPC response:', response); } catch (error) { console.error('RPC call failed:', error); } ``` -------------------------------- ### Verify Webhook Callbacks Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Decode and verify incoming webhook callbacks from LiveKit to ensure their authenticity. Ensure your server is configured to receive POST requests with 'application/webhook+json' Content-Type. ```typescript import { WebhookReceiver } from 'livekit-server-sdk'; const receiver = new WebhookReceiver('apikey', 'apisecret'); // In order to use the validator, WebhookReceiver must have access to the raw POSTed string (instead of a parsed JSON object) // if you are using express middleware, ensure that `express.raw` is used for the webhook endpoint // app.use(express.raw({type: 'application/webhook+json'})); app.post('/webhook-endpoint', async (req, res) => { // event is a WebhookEvent object const event = await receiver.receive(req.body, req.get('Authorization')); }); ``` -------------------------------- ### Webhook Verification Source: https://github.com/livekit/node-sdks/blob/main/packages/livekit-server-sdk/README.md Verify incoming webhook events from LiveKit to ensure their authenticity. This uses a `WebhookReceiver` instance. ```APIDOC ## WebhookReceiver ### Description Helper functions to decode and verify webhook callbacks from LiveKit. ### Constructor `new WebhookReceiver(apiKey: string, apiSecret: string)` ### Method `receive(rawBody: string, authorization: string | undefined): Promise` ### Description Decodes and verifies a webhook event. Requires the raw request body and the `Authorization` header. ### Example ```typescript import { WebhookReceiver } from 'livekit-server-sdk'; const receiver = new WebhookReceiver('apikey', 'apisecret'); // Ensure your server middleware is configured to provide the raw body // e.g., using express.raw({type: 'application/webhook+json'}) in Express app.post('/webhook-endpoint', async (req, res) => { const event = await receiver.receive(req.body, req.get('Authorization')); // Process the event }); ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.