Getting started with Sinch In-app Calling for JavaScript SDK

This guide shows you how to get started integrating your JavaScript application with the In-app Calling SDK. Because we're just getting started, this guide only covers how to sign in to the In-app Calling SDK and how to make and receive audio calls. For more complex examples and documentation, check our reference app or look into our documentation.

Prerequisites

  • Editor of choice
  • Latest version of Chrome web browser
  • An http server; for example http-server to host the files

Create project

Create an empty JavaScript file called index.js, and sw.js and an HTML file called index.html in the same folder.

Add Sinch Voice and Video SDK to your JavaScript application

  1. Add the following script tag to index.html in the <head>-section.
Copy
Copied
<script src="https://cdn.sinch.com/latest/sinch-rtc-min.js"></script>
  1. Add the following script tag to the bottom of index.html in the <body>-section
Copy
Copied
<script type="module" src="index.js"></script>
  1. Add the following JavaScript code to the sw.js file. It's a service worker for handling push notifications.
Copy
Copied
this.addEventListener("push", (event) => {
  console.log("ServiceWorker Push: ", event);
  const body = event.data.json();
  event.waitUntil(
    clients
      .matchAll({ includeUncontrolled: true, type: "window" })
      .then((clients) => {
        clients.forEach((client) => {
          client.postMessage({
            visible: client.visibilityState === "visible",
            data: body,
          });
        });
      })
  );
});

Interacting with Voice and Video SDK

The SinchClient object is the main SDK entry point. Once created it's used to provide various SDKs features such as video, audio, or telephone calls. We recommend to initiate SinchClient once and retain its instance during the entire lifetime of the running application.

In the index.js file, paste in the following code:

Copy
Copied
const APP_KEY = "enter-application-key";
const APP_SECRET = "enter-application-secret";
const ENVIRONMENT_HOST = "ocra.api.sinch.com";

class SinchClientWrapper {
  constructor(userId, ui) {
    this.userId = userId;
    this.ui = ui;

    const sinchClient = Sinch.getSinchClientBuilder()
      .applicationKey(APP_KEY)
      .userId(userId)
      .environmentHost(ENVIRONMENT_HOST)
      .build();

    sinchClient.addListener(this.#sinchClientListener());
    sinchClient.setSupportManagedPush();
    sinchClient.start();

    this.sinchClient = sinchClient;
  }
}

This creates a new SinchClientWrapper class and implements the constructor.

To make this example work for you, you need to update some values:

ParameterYour value
APP_KEYYou can find your key on your dashboard.
APP_SECRETYou can find your secret on your dashboard. Your secret is only available to view right after creating your key, so make sure you copy it somewhere safe.

There are a few other elements to notice:

  • The environmentHost parameter is the endpoint of the REST API the SDK is targeting.
  • The userId parameter is the user identifier to register within your application (the specific value will be provided after clicking Login button in the application).
  • The setSupportManagedPush parameter enables or disables the functionality of receiving notifications about incoming calls even when the application is not in the foreground.
    Note:

    It's almost certain that your production application should enable this feature. If not enabled it won't be possible to get notified about incoming calls.

When starting, the Sinch client SinchClientListener's onCredentialsRequired method executes. Inside this callback you must provide a signed (with your application secret) JWT token. In a production application the token should be generated on your backend infrastructure. Most importantly you shouldn't put your app secret value into your JavaScript application source code. More information on that topic can be found in Authentication & Authorization.

Just for this step-by-step guide purpose we will mimic a backend authentication server behaviour with a helper JWT class that creates the token based on userId and your application credentials locally and then passes it back to Sinch SDK:

Copy
Copied
class SinchClientWrapper {
  // constructor ...

  #sinchClientListener() {
    return {
      onCredentialsRequired: (sinchClient, clientRegistration) => {
        // TODO: implement this in a backend server
        new JWT(APP_KEY, APP_SECRET, this.userId)
          .toJwt()
          .then(clientRegistration.register)
          .catch((error) => {
            clientRegistration.registerFailed();
            console.error(error);
          });
      },
    };
  }
}

Implementation of the JWT class can be found in the reference app implementation here.

Communication between UI and Sinch client

To communicate between your application UI layer and the Sinch client we implement a reference to SinchClientWrapper in UI and a reference to UI from SinchClientWrapper.

  1. Inside index.js create a class named UI that handles login and creation of SinchClientWrapper, as demonstrated in the following example:
Copy
Copied
class UI {
  constructor() {
    this.#handleLogin();
    console.log("UI started");
  }

  #handleLogin() {
    document.getElementById("login").addEventListener("click", () => {
      const userId = document.getElementById("userid").value;
      this.#hideElement("login-container");
      this.sinchClientWrapper = new SinchClientWrapper(userId, this);
    });
  }

  #hideElement(id) {
    const element = document.getElementById(id);
    element.style = "display: none";
  }
}
  1. In bottom of index.js add the following JavaScript to instantiate the UI class.
Copy
Copied
new UI();

Logging into the application

When the user starts the application, usually they must enter a username that will be passed as userId and used to create a Sinch client. The username they choose will then be used as a callee identifier for making the actual audio call.

  1. Create a simple layout containg input fields and login button in index.html top <body>-section.
    Copy
    Copied
    <div id="login-container">
      <input id="userid" placeholder="Enter user id" type="text" />
      <button id="login">Login</button>
    </div>
  2. Return to SinchClientWrapper implementation. Inside onClientStarted and onClientFailed callbacks of SinchClientListener add the following log commands to print out messages to the console.
    Copy
    Copied
    class SinchClientWrapper {
      // constructor ...
    
      #sinchClientListener() {
        return {
          // onCredentialsRequired ...
    
          onClientStarted: (sinchClient) => {
            console.log("Sinch - Start client succeded");
          },
    
          onClientFailed: (sinchClient, error) => {
            console.log("Sinch - Start client failed");
            console.error(error);
          },
        };
      }
    }
  3. Run an http server from your working directory, go to index.html and enter a username to verify your browser console. You should see that the client was started successfully.

Next steps

Now that your application is created, you can configure that application to make a call.

Was this page helpful?