• Stars
    star
    124
  • Rank 288,207 (Top 6 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created almost 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

LiveKit real-time and server SDKs for Node.JS
The LiveKit icon, the name of the repository and some sample code in the background.

LiveKit Server API for JS

Use this SDK to manage LiveKit rooms and create access tokens from your JavaScript/Node.js backend.

Note

This is v2 of the server-sdk-js which runs in NodeJS, Deno and Bun! (It theoretically now also runs in every major browser, but that's not recommended due to the security risks involved with exposing your API secrets) Read the section below for a detailed overview on what has changed.

Migrate from v1.x to v2.x

Token generation

Because the jsonwebtoken lib got replaced with jose, there are a couple of APIs that are now async, that weren't before:

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();

// v1
// const grants = v.verify(token);

// v2
const grants = await v.verify(token);

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'));
});

Egress API

Egress request types have been updated from interfaces to classes in the latest version. Additionally, oneof fields now require an explicit case field to specify the value type.

For example, to create a RoomComposite Egress:

// v1
// const fileOutput = {
//   fileType: EncodedFileType.MP4,
//   filepath: 'livekit-demo/room-composite-test.mp4',
//   s3: {
//     accessKey: 'aws-access-key',
//     secret: 'aws-access-secret',
//     region: 'aws-region',
//     bucket: 'my-bucket',
//   },
// };

// const info = await egressClient.startRoomCompositeEgress('my-room', {
//   file: fileOutput,
// });

// v2 - current
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,
});

Installation

Pnpm

pnpm add livekit-server-sdk

Yarn

yarn add livekit-server-sdk

NPM

npm install livekit-server-sdk --save

Usage

Environment Variables

You may store credentials in environment variables. If api-key or api-secret is not passed in when creating a RoomServiceClient or AccessToken, the values in the following env vars will be used:

  • LIVEKIT_API_KEY
  • LIVEKIT_API_SECRET

Creating Access Tokens

Creating a token for participant to join a room.

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);

By default, the token expires after 6 hours. you may override this by passing in ttl in the access token options. ttl is expressed in seconds (as number) or a string describing a time span vercel/ms. eg: '2 days', '10h'.

Permissions in Access Tokens

It's possible to customize the permissions of each participant:

const at = new AccessToken('api-key', 'secret-key', {
  identity: participantName,
});

at.addGrant({
  roomJoin: true,
  room: roomName,
  canPublish: false,
  canSubscribe: true,
});

This will allow the participant to subscribe to tracks, but not publish their own to the room.

Managing Rooms

RoomServiceClient gives you APIs to list, create, and delete rooms. It also requires a pair of api key/secret key to operate.

import { RoomServiceClient, Room } 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,
};
svc.createRoom(opts).then((room: Room) => {
  console.log('room created', room);
});

// delete a room
svc.deleteRoom('myroom').then(() => {
  console.log('room deleted');
});

Webhooks

The JS SDK also provides helper functions to decode and verify webhook callbacks. While verification is optional, it ensures the authenticity of the message. See webhooks guide for details.

LiveKit POSTs to webhook endpoints with Content-Type: application/webhook+json. Please ensure your server is able to receive POST body with that MIME.

Check out example projects for full examples of webhooks integration.

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'));
});


LiveKit Ecosystem
Client SDKsComponents Β· JavaScript Β· iOS/macOS Β· Android Β· Flutter Β· React Native Β· Rust Β· Python Β· Unity (web) Β· Unity (beta)
Server SDKsNode.js Β· Golang Β· Ruby Β· Java/Kotlin Β· PHP (community) Β· Python (community)
ServicesLivekit server Β· Egress Β· Ingress
ResourcesDocs Β· Example apps Β· Cloud Β· Self-hosting Β· CLI

More Repositories

1

livekit

End-to-end stack for WebRTC. SFU media server and SDKs.
Go
9,214
star
2

agents

Build real-time multimodal AI applications πŸ€–πŸŽ™οΈπŸ“Ή
Python
750
star
3

client-sdk-js

LiveKit browser client SDK (javascript)
TypeScript
329
star
4

client-sdk-flutter

Flutter Client SDK for LiveKit
Dart
238
star
5

livekit-cli

Command line interface to LiveKit
Go
199
star
6

server-sdk-go

Client and server SDK for Golang
Go
189
star
7

client-sdk-swift

LiveKit Swift Client SDK. Easily build live audio or video experiences into your mobile app, game or website.
Swift
182
star
8

rust-sdks

LiveKit real-time and server SDKs for Rust
Rust
173
star
9

client-sdk-android

LiveKit SDK for Android
Kotlin
169
star
10

livekit-react

React component and library for LiveKit
TypeScript
169
star
11

egress

Export and record WebRTC sessions and tracks
Go
166
star
12

components-js

Official open source React components and examples for building with LiveKit.
TypeScript
145
star
13

client-sdk-react-native

TypeScript
98
star
14

python-sdks

LiveKit real-time and server SDKs for Python
Python
80
star
15

sip

SIP to WebRTC bridge for LiveKit
Go
76
star
16

protocol

LiveKit protocol. Protobuf definitions for LiveKit's signaling protocol
Go
69
star
17

ingress

Ingest streams (RTMP/WHIP) or files (HLS, MP4) to LiveKit WebRTC
Go
68
star
18

agents-playground

TypeScript
61
star
19

client-sdk-unity-web

Client SDK for Unity WebGL
C#
50
star
20

livekit-helm

LiveKit Helm charts
Smarty
47
star
21

livekit-recorder

Go
32
star
22

client-sdk-unity

C#
31
star
23

track-processors-js

TypeScript
29
star
24

server-sdk-kotlin

Kotlin
28
star
25

livekit-server-sdk-python

LiveKit Server SDK for Python
Python
25
star
26

psrpc

Go
22
star
27

client-example-swift

Example app for LiveKit Swift SDK πŸ‘‰ https://github.com/livekit/client-sdk-swift
Swift
21
star
28

server-sdk-ruby

LiveKit Server SDK for Ruby
Ruby
21
star
29

meet

Open source video conferencing app built on LiveKit Components, LiveKit Cloud, and Next.js.
TypeScript
16
star
30

client-unity-demo

Demo for LiveKit Unity SDK
C#
11
star
31

client-sdk-cpp

C++
11
star
32

WebRTC-swift

Swift package for WebRTC
Objective-C
10
star
33

livekit-docs

JavaScript
10
star
34

deploy

Resources for deploying LiveKit
Go
9
star
35

webrtc-vmaf

VMAF benchmarking tool for WebRTC codecs
Python
9
star
36

chrometester

A livekit tester to simulate a subscriber in a room, uses headless Chromium
JavaScript
8
star
37

gstreamer-publisher

Command-line app that publishes any GStreamer pipeline to LiveKit
Go
8
star
38

nats-test

benchmarking app that emulates our usage patterns
Go
7
star
39

mediatransportutil

Media transport utilities
Go
6
star
40

rtcscore-go

Library to calculate Mean Opinion Score(MOS)
Go
4
star
41

components-swift

Swift
4
star
42

signal-proxy

Go
3
star
43

client-example-collection-swift

A collection of small examples for the LiveKit Swift SDK πŸ‘‰ https://github.com/livekit/client-sdk-swift
Swift
3
star
44

webrtc-chrome

Fork of Google's WebRTC repo, with LiveKit patches.
C++
3
star
45

components-android

Kotlin
3
star
46

gst-plugins

Go
3
star
47

client-sdk-react-native-expo-plugin

TypeScript
2
star
48

webrtc-xcframework

Ruby
2
star
49

mageutil

Go
2
star
50

ios-test-apps

Swift
1
star
51

gstreamer

C
1
star
52

websocket-bridge

Send and Receive Media to LiveKit via WebSocket
Go
1
star