Skip to content

Node#

Source code

This is a minimal server application built for Node with Express that allows:

It internally uses LiveKit JS SDK.

Running this application#

Download the tutorial code:

git clone https://github.com/OpenVidu/openvidu-livekit-tutorials.git

To run this server application, you need Node installed on your device.

  1. Navigate into the server directory
    cd openvidu-livekit-tutorials/application-server/node
    
  2. Install dependencies
    npm install
    
  3. Run the application
    npm start
    

Info

You can run any Application Client to test against this server right away.

Understanding the code#

The application is a simple Express app with a single file index.js that exports two endpoints:

  • /token : generate a token for a given Room name and Participant name.
  • /livekit/webhook : receive LiveKit webhook events.

Let's see the code of the index.js file:

index.js
import "dotenv/config";
import express from "express";
import cors from "cors";
import { AccessToken, WebhookReceiver } from "livekit-server-sdk"; // (1)!

const SERVER_PORT = process.env.SERVER_PORT || 6080; // (2)!
const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY || "devkey"; // (3)!
const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET || "secret"; // (4)!

const app = express(); // (5)!

app.use(cors()); // (6)!
app.use(express.json()); // (7)!
app.use(express.raw({ type: "application/webhook+json" })); // (8)!
  1. Import AccessToken from livekit-server-sdk.
  2. The port where the application will be listening.
  3. The API key of LiveKit Server.
  4. The API secret of LiveKit Server.
  5. Initialize the Express application.
  6. Enable CORS support.
  7. Enable JSON body parsing for the /token endpoint.
  8. Enable raw body parsing for the /livekit/webhook endpoint.

The index.js file imports the required dependencies and loads the necessary environment variables:

  • SERVER_PORT: the port where the application will be listening.
  • LIVEKIT_API_KEY: the API key of LiveKit Server.
  • LIVEKIT_API_SECRET: the API secret of LiveKit Server.

It also initializes the WebhookReceiver object that will help validating and decoding incoming webhook events.

Finally the express application is initialized. CORS is allowed, JSON body parsing is enabled for the /token endpoint and raw body parsing is enabled for the /livekit/webhook endpoint.


Create token#

The endpoint /token accepts POST requests with a payload of type application/json, containing the following fields:

  • roomName: the name of the Room where the user wants to connect.
  • participantName: the name of the participant that wants to connect to the Room.
index.js
app.post("/token", async (req, res) => {
  const roomName = req.body.roomName;
  const participantName = req.body.participantName;

  if (!roomName || !participantName) {
    res.status(400).json({ errorMessage: "roomName and participantName are required" });
    return;
  }

  const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, { // (1)!
    identity: participantName,
  });
  at.addGrant({ roomJoin: true, room: roomName }); // (2)!
  const token = await at.toJwt(); // (3)!
  res.json({ token }); // (4)!
});
  1. A new AccessToken is created providing the LIVEKIT_API_KEY, LIVEKIT_API_SECRET and setting the participant's identity.
  2. We set the video grants in the AccessToken. roomJoin allows the user to join a room and room determines the specific room. Check out all Video Grants.
  3. We convert the AccessToken to a JWT token.
  4. Finally, the token is sent back to the client.

The endpoint first obtains the roomName and participantName parameters from the request body. If they are not available, it returns a 400 error.

If required fields are available, a new JWT token is created. For that we use the LiveKit JS SDK:

  1. A new AccessToken is created providing the LIVEKIT_API_KEY, LIVEKIT_API_SECRET and setting the participant's identity.
  2. We set the video grants in the AccessToken. roomJoin allows the user to join a room and room determines the specific room. Check out all Video Grants.
  3. We convert the AccessToken to a JWT token.
  4. Finally, the token is sent back to the client.

Receive webhook#

The endpoint /livekit/webhook accepts POST requests with a payload of type application/webhook+json. This is the endpoint where LiveKit Server will send webhook events.

index.js
const webhookReceiver = new WebhookReceiver( // (1)!
  LIVEKIT_API_KEY,
  LIVEKIT_API_SECRET
);

app.post("/livekit/webhook", async (req, res) => {
  try {
    const event = await webhookReceiver.receive(
      req.body, // (2)!
      req.get("Authorization") // (3)!
    );
    console.log(event); // (4)!
  } catch (error) {
    console.error("Error validating webhook event", error);
  }
  res.status(200).send();
});
  1. Initialize the WebhookReceiver using the LIVEKIT_API_KEY and LIVEKIT_API_SECRET. It will help validating and decoding incoming webhook events.
  2. The body of the HTTP request.
  3. The Authorization header of the HTTP request.
  4. Consume the event as you whish.

First of all we initialize the WebhookReceiver using the LIVEKIT_API_KEY and LIVEKIT_API_SECRET. This object will validate and decode the incoming webhook events.

The endpoint receives the incoming webhook with the async method WebhookReceiver#receive. It takes the body and the Authorization header of the request. If everything is correct, you can do whatever you want with the event (in this case, we just log it).

Remember to return a 200 OK response at the end to let LiveKit Server know that the webhook was received correctly.


From production to a local server#

When developing locally pointing to a production deployment and webhooks events are required by your application, you might face issues because OpenVidu cannot access your local server.

To receive webhooks from OpenVidu on your local machine, you need to expose your local server to the internet. This exposure allows OpenVidu to send webhooks directly to your local server.

The following images illustrate the difference between an unreachable local server and a reachable local server:

Unreachable local server

Unreachable local server

Reachable local server

Reachable local server

Exposing your local server to the internet is a common practice when developing applications locally. Tools like Ngrok, LocalTunnel, LocalXpose and Zrok can help you achieve this.

These tools provide you with a public URL that forwards requests to your local server. You can use this URL to receive webhooks from OpenVidu. For information on how to add this URL as the webhook URL in the OpenVidu deployment, refer to the following documentation:

  • Configure webhooks for an OpenVidu Local deployment. Learn more.
  • Configure webhooks for an OpenVidu Single Node deployment. Learn more.
  • Configure webhooks for an OpenVidu Elastic On-Premises deployment. Learn more.

  • Configure webhooks for an OpenVidu Elastic AWS deployment. Learn more.

  • Configure webhooks for an OpenVidu High Availability On-Premises deployment. Learn more.

  • Configure webhooks for an OpenVidu High Availability AWS deployment. Learn more.