kaltura with typescript

Connecting with Kaltura from NodeJs using Kaltura TypeScript Client

Imagine a multinational company planning a grand product launch for their latest gadget. 

They want to broadcast the event live to their global audience, ensuring that customers, media, and stakeholders can tune in from anywhere in the world. 

The event includes presentations, product demos, and interviews with key figures. Let’s discover how to seamlessly integrate video management by connecting with Kaltura from NodeJs using Kaltura TypeScript Client.

Or Imagine you’re managing a popular online learning platform that streams educational videos to thousands of students globally. 

Your platform needs a robust video management solution to handle video uploads, processing, streaming, and analytics. 

Enter Kaltura, a powerful video platform that can simplify these tasks.

But how do you integrate Kaltura with your NodeJs backend seamlessly? 

That’s where the Kaltura TypeScript client comes into play.

Recently when I was working on a project, I found myself looking for a better way to upload a video on Kaltura from a NodeJs project. Of course, there is a Kaltura npm library that can be used to upload videos and do other things on Kaltura, but it didn’t work out for us, so we switched to Kaltura TypeScript client

Motivation

Our main objective was to be able to create a media entry on Kaltura and upload a video on that entry using a URL. And while creating the media entry, we will provide some video metadata like title, description, etc. And these metadata may contain some Danish characters.

We are using TypeScript as our coding language, so I was looking for a typed Kaltura client library to use for our objective. But unfortunately at that time, we didn’t find the Kaltura TypeScript client library, so we made work with the npm library. It was doing fine until we found that if we try to create an entry that contains any Danish characters, it fails in the code giving some errors. At first, we thought it was a problem with Kaltura API, but after some debugging and some chat with Kaltura support, we realized that the error was in the npm library. So I started looking for an alternative and that is when I found the Kaltura TypeScript client on the Kaltura native libraries page.

Source code

You can get the full project code in this GitHub project. The initial project code is in the master branch and a full working code that connects to Kaltura lies in the develop branch. You can download the code and use it as a reference to get going.

Code Setup

For this demonstration, I’ll create a new NodeJs project. Initially, the project structure is like this:

Connecting with Kaltura from NodeJs using Kaltura TypeScript Client

You can grab the project from the GitHub repo. The master branch contains the initial project structure shown in the image above.

Adding the Kaltura Library

To use the Kaltura TypeScript client, first, clone the library from GitHub. After that go to the project directory and run the following commands:

$ npm install
$ npm run deploy

 

This will create a folder in the working directory named dist, where the main TypeScript library can be found, which is named like: kaltura-typescript-client-<version_name>.tgz

Connecting with Kaltura from NodeJs using Kaltura TypeScript Client

Now we need to place this file in the project that we created before. I’ll put the file in the lib directory of the project. For simplicity, I’ll rename the file to kaltura-typescript-client-7.0.1.tgz. But you can leave it as it is.

Connecting with Kaltura from NodeJs using Kaltura TypeScript Client

Now open the package.json file and add the following into the “dependencies” block:

 

kaltura-typescript-client": "file:lib/kaltura-typescript-client-7.0.1.tgz
Connecting with Kaltura from NodeJs using Kaltura TypeScript Client
Add the library located inside the dependencies block in the package.json file

After that just open any terminal, go to the project root and execute:

$ npm install

That’s it, you have successfully added the Kaltura TypeScript library into your NodeJs project. All that’s left is to apply it in code and connect to Kaltura and do whatever you want to do.

Connecting to Kaltura

To test that our library integration is working, it’s best to connect to the Kaltura developer account and get the session token.

First, let’s add a new file named kalturaService.ts in the src > util folder. In this file, we will add the necessary methods to connect to the Kaltura API.

Connecting with Kaltura from NodeJs using Kaltura TypeScript Client

Paste the following code into the kalturaService.ts file.

import { KalturaClient } from "kaltura-typescript-client";
import { KalturaSessionType } from "kaltura-typescript-client/api/types/KalturaSessionType";
import { SessionStartAction } from "kaltura-typescript-client/api/types/SessionStartAction";
global.XMLHttpRequest = require("xhr2");

const config = {
  clientTag: "Kaltura_typescript_testing",
  endpointUrl: "http://www.kaltura.com",
};

const client = new KalturaClient(config);

export const startKalturaSession = async (
  adminSecret: string,
  userSecret: string,
  partnerId: number
): Promise<boolean> => {
  try {
    const session = await client.request(
      new SessionStartAction({
        partnerId,
        secret: adminSecret,
        userId: userSecret,
        type: KalturaSessionType.admin,
      })
    );

    if (!session) {
      console.log("Failed to start Kaltura session");
      return false;
    }

    client.setDefaultRequestOptions({ ks: session });
    console.log(`Kaltura session:\n${session}`);
    return true;
  } catch (error) {
    console.log(`Kaltura session error: \n ${error}`);
    return false;
  }
};

Here, give extra attention in the following line in the code:

global.XMLHttpRequest = require("xhr2");

This line set’s the XMLHttpRequest from xhr2 npm library, because in the Kaltura TypeScript library, it uses XMLHttpRequest to connect to Kaltura API. If you don’t add this line you might get an error: ReferenceError: XMLHttpRequest is not defined. To avoid that, add xhr2 npm library by running the following command on the terminal from the project root. And while we are at it, we will be needing another npm library, dotenvwhich will be used to get the Kaltura account credentials from the .env file, which we will create just after a little bit.

$ npm install -D xhr2 dotenv

Now it’s time to use the file we just created to get the session token of Kaltura. Copy the following code and paste it into the index.ts file.

import { startKalturaSession } from "./util/kalturaService";
import * as env from 'dotenv';

const run = async () => {
  console.log("This project is for testing the Kaltura TypeScript library");
  
  // Load environment variables from .env file
  env.config();
  
  // Retrieve Kaltura credentials from environment variables
  const adminSecret = process.env.adminSecret;
  const userSecret = process.env.userSecret;
  const partnerId = process.env.partnerId;
  
  // Check if all required credentials are available
  if (!adminSecret || !userSecret || !partnerId) {
    console.log("Please check your Kaltura credentials in .env file and try again");
    return;
  }
  
  // Start Kaltura session with retrieved credentials
  const sessionStarted = await startKalturaSession(
    adminSecret,
    userSecret,
    Number(partnerId)
  );
  
  // Check if session started successfully
  if (sessionStarted) {
    console.log("Successfully got the Kaltura session");
  } else {
    console.log("Failed to get the Kaltura session token");
  }
};

// Execute the run function to start the process
run();

Here we are getting the adminSecret, userSecret, partnerId that we need to connect to the Kaltura API. You can find these credential info by following these steps:

  1. Login to the Kaltura management console. If you don’t have an account, just create a new one from here.
  2. Click the Settings icon or click here to directly go to the settings page.
Connecting with Kaltura from NodeJs using Kaltura TypeScript Client

3. Select the INTEGRATIONtab, or click here to directly open the page. There you will find all the necessary info needed for this testing.

Connecting with Kaltura from NodeJs using Kaltura TypeScript Client
Kaltura Integration settings page where all necessary credentials are placed.

Now just copy the .env.example file from the GitHub project or copy the content of the file from here and then create a new file named .env and paste the copied code in the .env file.

That’s it, now you are ready to run the code! Just hit npm start from the terminal or cmd and you should get a success message: “Successfully got the Kaltura session” with the Kaltura session token! You now do whatever you want on Kaltura using this TypeScript library. To get to know what you can do and how to do it, visit the Kaltura API documentation, where you will also find the code snippet for your desired work.

Why Use Kaltura with NodeJs?

Before diving into the technical details, let’s understand why you might need this solution:

  1. Educational Platforms: Like our example, online learning platforms often require extensive video management capabilities.
  2. Corporate Training: Companies providing internal training or product demos through video content can benefit from Kaltura’s comprehensive video solutions.
  3. Media and Entertainment: Media companies that manage large libraries of video content need reliable tools to handle video processing and distribution.
  4. Healthcare: Telehealth services often use video for consultations, and Kaltura can help manage these video interactions efficiently.

How It Helps

  1. Live Streaming: Kaltura’s robust platform supports high-quality live streaming, ensuring the event is accessible in real time to a global audience.
  2. Scalability: The platform can handle thousands of concurrent viewers without compromising on performance.
  3. Post-Event Content Management: Once the live event is over, the recorded content can be processed, edited, and made available on-demand through the same platform.
  4. Analytics: Kaltura provides detailed analytics on viewer engagement, helping the company understand the reach and impact of its product launch.

Examples of Businesses Using Kaltura for Broadcasting and Streamlining

1. University of Melbourne

Use Case: Online Learning and Live Lectures

The University of Melbourne uses Kaltura to manage and deliver its online learning content. The platform is used to livestream lectures, seminars, and other academic events to students globally. With Kaltura, they can:

  • Stream live lectures: Allowing remote students to attend in real-time.
  • Manage video content: Organizing recorded lectures for on-demand access.
  • Analyze engagement: Using analytics to understand student interaction with the content.

2. Nestlé

Use Case: Corporate Training and Internal Communications

Nestlé utilizes Kaltura for its corporate training programs and internal communications. The platform enables them to:

  • Broadcast live training sessions: Ensuring consistent training across global offices.
  • Streamline internal communications: Hosting live town halls and executive announcements.
  • Provide on-demand training: Offering recorded sessions for new employees and continuous learning.

3. ViacomCBS

Use Case: Media and Entertainment

ViacomCBS leverages Kaltura to manage its vast library of video content and for live streaming events. They benefit from:

  • Live broadcasting: Streaming live TV shows and events to a global audience.
  • Content management: Organizing and distributing on-demand video content.
  • Viewer analytics: Gathering insights into viewer preferences and behavior.

4. NHS (National Health Service) UK

Use Case: Telehealth and Medical Training

The NHS uses Kaltura for both telehealth services and medical training. Kaltura helps them to:

  • Stream medical consultations: Enabling remote patient consultations and follow-ups.
  • Provide training: Offering live and recorded training sessions for medical staff.
  • Enhance patient education: Sharing educational videos on health topics with patients.

5. HBO

Use Case: Content Distribution and Viewer Engagement

HBO uses Kaltura to distribute and manage its premium video content. The platform supports:

  1. Live event streaming: Broadcasting premieres and special events.
  2. On-demand content: Managing and distributing TV shows and movies.
  3. Engagement analytics: Tracking viewer engagement and preferences.

 

  1. Security: Ensures the broadcast is secure, preventing unauthorized access and content piracy.

Conclusion

These examples and real-life setups for a client illustrate how diverse organizations across various industries are leveraging Kaltura’s robust video platform for broadcasting and streamlining their video content. From education and corporate training to media and healthcare, Kaltura offers scalable and customizable solutions to meet the unique needs of each business. By integrating Kaltura with a NodeJs backend using the Kaltura TypeScript client, these organizations can deliver high-quality video experiences, enhance audience engagement, and streamline content management.

 

Picture of Asif Imtiaj Safi

Asif Imtiaj Safi

Software Development Engineer

Hire Exceptional Developers Quickly

Share this blog on

Hire Your Software Development Team

Let us help you pull out your hassle recruiting potential software engineers and get the ultimate result exceeding your needs.

Contact Us Directly

Address:

Plot # 272, Lane # 3 (Eastern Road) DOHS Baridhara, Dhaka 1206

Talk to Us
Scroll to Top