Start enriching your app
No Credit Card Required

Docs

JavaScript

Introduction

The Sinch SDK is a product that makes adding voice calling and/or instant messaging to web apps easy. It handles the complexity of signaling and audio management while providing you the freedom to create a stunning user interface. The current release supports instant messaging, web to phone calling and web to web calling as well as web to app calling.

This document provides an overview for developers integrating with the Sinch SDK for the first time. It outlines the prerequisites and guides you through the process of placing calls from a web application or sending and receiving instant messages.

Please see the Reference Documentation for a comprehensive description of all the classes.

Please note: Should you encounter any bugs, glitches, lack of functionality or other problems using our SDK, please send us an email to dev@sinch.com.

Your help in this regard is greatly appreciated.

First time setup

This is a step-by-step guide about setting up the Sinch SDK for the first time.

Register an Application

  1. Register a Sinch Developer account at http://www.sinch.com/signup.
  2. Setup a new Application using the Dashboard where you can then obtain an Application Key and Application Secret.

Download

The Sinch SDK can be downloaded at www.sinch.com/downloads/. It contains: the Sinch JS SDK, this user guide, reference documentation, and sample apps.

Running sample apps

Make sure you configure your application key in the sample apps by replacing the placeholder text “MY_APPLICATION_KEY” with your key. Samples can be run in the browser as files by double-clicking the index.html file. Make sure you open the developer console in your browser to catch possible error messages.

Note: Currently, calling only works in the Chrome or Firefox browsers. Chrome additionally requires the web page to be loaded using http or https and is not compatible with local storage (i.e., file://).

Development

There are many ways to include Sinch in your project, enabling you to select a suitable method depending on how your project is set up.

Hosted with your webapp

You can host the library co-located with your website and include Sinch using

<script src="sinch.min.js"></script>

Load from Sinch CDN

If you prefer to always load the latest version from our CDN, use

<script src="//cdn.sinch.com/latest/sinch.min.js"></script>

To control which version you load from our CDN, use

<script src="//cdn.sinch.com/0.0.1/sinch.min.js"></script>

Sinch is available as a npm package

If you are using NodeJS, add a dependency to Sinch by running:

npm install sinch-rtc --save

Note: The –save flag is optional for saving the dependency in package.json

Import Sinch SDK in your project using

var SinchClient = require('sinch-rtc');

Sinch is available as a Bower module

If you are using Bower, add a dependency to Sinch by running:

bower install sinch-rtc --save

Import the Sinch SDK in your website using

<script src="PATH_TO_BOWER_MODULES/sinch-rtc/sinch.min.js"></script>

Note: The –save flag is optional for saving the dependency in bower.json

Sinch client

The SinchClient class is the SDK entry point. It is used to configure the user’s and device’s capabilities, as well as providing access to feature classes such as the MessageClient and the CallClient.

Instantiating the SinchClient

In order to use Sinch you first need to create a “sinchClient” object using the application key and other options of your choice.

var sinchClient = new SinchClient({
    applicationKey: '<application_key>',
    capabilities: {messaging: true},
});

The <application_key> is obtained from the Sinch Developer Dashboard. In this example, only the messaging capability is activated.

Specifying capabilities

The sinchClient can be configured to enable / disable certain functionality. Please see the Reference Documentation for details.

The following example shows how to setup the client with both voice calling and instant messaging enabled.

var sinchClient = new SinchClient({
    applicationKey: '<application_key>',
    capabilities: {messaging: true, calling: true},
    supportActiveConnection: true,
});

Creating the client using supportActiveConnection: true will enable online capabilities for receiving incoming calls and messages. If application is started in this way, connection can be activated at any time using sinchClient.startActiveConnection(). Starting and stopping the connection can be done repeatedly. When your application expects incoming messages or calls, you should keep the connection open. In a future release, the Sinch JS SDK will be able to fall back to browser notifications if no active connection is available.

Note: If application is only making outgoing PSTN calls but not receive incoming calls or messages, don’t call sinchClient.startActiveConnection(). Outgoing calls can be made without the active connection since it will automatically start the signaling channel as needed.

Starting the Sinch client

A SinchClient is started with an object describing the identity of the user.

sinchClient.start({username: '<user id>', password: '<password>'})

When starting Sinch, supplying a user identity with password is one way of starting the client; use this when you want Sinch to manage your users for you.

If you prefer to manage your users yourself, and/or select a third party provider, a SinchClient instance can also be started using a valid authentication ticket. Please see the chapter on authentication for an overview of Sinch user identity management and options for managing your own users. There is also a sample app, SinchAUTHsample, which demonstrates this concept.

Asynchronous Sinch Calls

The Sinch SDK contains many asynchronous methods. Several network requests are made in the background when making certain method calls and, while this happens, your code will continue to execute.

When using asynchronous methods in Sinch, there are two ways of acting on the result. All asynchronous methods accept two callbacks as additional parameters, first the success callback, then the fail callback.

Additionally, all asynchronous methods in Sinch also return a promise, which will either be resolved or rejected. If it’s resolved the next method in the chain, which is specified using .then(), will be called. If there is an failure, the method specified in .fail() will be called.

Sinch with callbacks

var handleSuccess = function() {...};
var handleFail = function() {...};

sinchClient.start(loginObj, handleSuccess, handleFail);

Sinch with promises

var handleSuccess = function() {...};
var handleFail = function() {...};

sinchClient.start(loginObj)
    .then(handleSuccess)
    .fail(handleFail);

The benefit of using promises is that it’s easy to make a chain of method calls and the code will be clearer, but either method works fine.

Note: If both callbacks and promises are used, the execution order are for callbacks to be executed first followed by the methods in the promise-chain, specified using .then()

Calling

The Sinch SDK supports four types of calls: web-to-web (or app) calls, web-to-phone calls, web-to-sip and conference calls. The CallClient is the entry point for the calling functionality of the Sinch SDK. At the moment, calling is only supported in Chrome and Firefox, and we hope to add support in more browsers later on. The CallClient is the entry point for the calling functionality of the Sinch SDK.

Calls are placed through the CallClient and general events are received through eventListener callback on CallClient. The call client is owned by the SinchClient and accessed using sinchClient.getCallClient(). When a call is placed, a new call object is generated. It’s possible to add eventListener` callbacks on the created call-object, to listen for events related to this call, such as when the call state changes.

Calling is not enabled by default. Enable calling by instantiating SinchClient in the following way:

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true}});

Set up a web-to-web (or app) call

Use the CallClient to start the call (the callUser method). Pass the user identifier of the callee (the user receiving the call) to the call method, so that Sinch services can connect the call to the callee.

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true}});
var call = sinchClient.callUser('<remote user id>');
call.addEventListener(...); 

A call object is returned, containing details about the participants in the call, call details such as start time, call state, possible errors, and so on.

Assuming any of callee’s apps are available, the method onCallProgressing is called on the CallListener. It notifies the application that the outgoing call is progressing. If a progress tone should be played, this is where it should be started.

When the other party answers, the onCallEstablished method is called. Now, the users can start talking. If a progress tone was previously played, it should be stopped now. This is also where the incoming audio stream can be connected to a HTML audio element:

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true}});

var callListeners = {
    onCallEstablished: function(call) {
        $('audio').attr('src', call.incomingStreamURL); //If audio element has attribute "autoplay"
    },
}

var callClient = sinchClient.getCallClient();
var call = callClient.callUser('<remote user id>');
call.addEventListener(callListeners);

Note: If the audio is not connected properly to the audio element, as shown above, there will be no sound.

Set up an web-to-phone call

An web-to-phone call is a call that is made to a phone on the regular telephone network. Setting up an web-to-phone call is not much different from setting up a web-to-web call. Instead of invoking the callUser method, invoke the callPhoneNumber method on the CallClient object. Sufficient funds must be available on the Sinch account and a valid phone number specified for the call to connect successfully. The phone number should be specified according to the E.164 number formatting (http://en.wikipedia.org/wiki/E.164) recommendation and should be prefixed with a ‘+’. E.g. to call the US phone number 415 555 0101, the phone number should be specified as “+14155550101”. The ‘+’ is the required prefix and the US country code ‘1’ prepended to the local subscriber number.

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true}});

var callListeners = {
    onCallEstablished: function(call) {
        $('audio').attr('src', call.incomingStreamURL); //If audio element has attribute "autoplay"
    },
}

var call = callClient.callPhoneNumber('+46000000000');
call.addEventListener(callListeners);

Placing an web-to-phone call requires a developer account with credits. Topping up credits can be done on the Account page. Credits are used each time an web-to-phone call is placed and the balance history is updated after each call.

Web-to-phone calls can be tested by calling the following test number: +46000000000. When placing a call to this number, you will hear a voice prompt stating that the call has been connected, and shortly after that the call will automatically be ended.

Setting up an app-to-sip call

An app-to-sip call is a call that is made to a SIP server. Setting up an app-to-sip call is not much different from setting up an app-to-app call. Instead of invoking the callUser method, invoke the callSip method on the CallClient object. The SIP identity follows the form of email addresses (user@domain), for example Alice@SipProviderA.com.

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true}});

var callListeners = {
    onCallEstablished: function(call) {
        $('audio').attr('src', call.incomingStreamURL); //If audio element has attribute "autoplay"
    },
}

var call = callClient.callSip('Alice@SipProviderA.com');
call.addEventListener(callListeners);

When customized SIP headers are passed as a parameter, the headers should be prefixed with ‘x-’.

Set up a conference call

A conference call can be made to connect a user to a conference room where multiple users can be connected at the same time. The identifier for a conference room may not be longer than 64 characters.

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true}});

var callListeners = {
    onCallEstablished: function(call) {
        $('audio').attr('src', call.incomingStreamURL); //If audio element has attribute "autoplay"
    },
}

var call = callClient.callConference('CONFERENCE_ROOM_HASH');
call.addEventListener(callListeners);

It is also possible to connect users to a conference call via the Sinch REST API.

Play ringback tone

For a good user experience, users expect a ringback tone while waiting for receiving end to pick up the phone. For this purpose, the following eventListener for a call may be a good template.

var callListeners = {
    onCallProgressing: function(call) {
        $('audio#ringback').prop("currentTime",0); //Ensure ringback start from beginning
        $('audio#ringback').trigger("play"); //Play ringback when call is progressing
    },
    onCallEstablished: function(call) {
        $('audio#ringback').trigger("pause"); //End ringback

        $('audio#incoming').attr('src', call.incomingStreamURL); //Connect incoming stream to audio element
    },
    onCallEnded: function(call) {
        $('audio#ringback').trigger("pause"); //End the ringback
        $('audio#incoming').attr('src', ''); //Ensure no incoming stream is playing

        //Optional: Enable user interface to make another call
    }
}

Handle incoming calls

In order to receive calls, SinchClient must be instantiated with configuration option supportActiveConnection set to true and invoking startActiveConnection after your SinchClient has successfully started.

var sinchClient = new SinchClient({
    applicationKey: '<application_key>',
    capabilities: {calling: true},
    supportActiveConnection: true,
});

To answer calls, the application must be notified when the user receives an incoming call.

Add a eventListener to the CallClient to act on the incoming calls. The eventListener is notified using onIncomingCall as calls come in to the application.

CallClient callClient = sinchClient.getCallClient();

callClient.addEventListener({
    onIncomingCall: function(incomingCall) {...}
});

When the incoming call method is executed, the call can either be connected automatically without any user action, or it can wait for the user to press the answer or the hangup button. If the call is set up to wait for a user response, we recommended that a ringtone is played to notify the user that there is an incoming call.

callClient.addEventListener({
    onIncomingCall: function(incomingCall) {
        //Play some groovy tunes & show UI
        ...
        //Add event listeners to the new call object representing the incoming call
        incomingCall.addEventListener(callListeners);
    }
});

To get events related to the call, add a call listener. The call object contains details about participants, start time, potential error codes, and error messages.

Answer incoming call

To answer the call, use the answer method on the call to accept it. If a ringtone was previously played, it should be stopped now.

User presses the answer button:

// User answers the call
call.answer();
// Stop playing ringing tone
...

Now, the clients on both ends establish the connection. When the call is established and the voice streams are running in both directions, the onCallEstablished listener method is called. In this listener method you should connect the incoming audio to an HTML audio element to hear the other side.

Decline incoming call

If the call should not be answered, use the hangup method on the call to decline. The caller is notified that the incoming call was denied. If a ringtone was previously played, it should be stopped now.

User presses the hangup button:

// User does not want to answer
call.hangup();
// Stop playing ringing tone
...

Disconnecting a Call

When the user wants to disconnect an ongoing call, use the hangup method. Either user taking part in a call can disconnect it.

Hanging up a call:

call.hangup();

When either party disconnects a call, the application is notified using the call listener method onCallEnded. This allows the user interface to be updated, an alert tone to be played, or similar actions to occur.

A call can be disconnected before it has been completely established.

Hanging up a connecting call:

// Starting a call
var call = callClient.callPhoneNumber("<remote participant>");

// User changed his/her mind, let’s hangup
call.hangup();

Video calling

Video calling can be activated for data calling by adding the capability “video” when starting the client. With this capability, video will now be added to all data-calls. Web to phone (PSTN) calling will be unaffected. A video call is set up in the same way as a voice only call:

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true, video: true}}); // Notice the video capability
var call = sinchClient.callUser('<remote user id>');
call.addEventListener(...); 

For callbacks, hangup and other methods on the call object when performing a video call, please reference the API docs for audio-only calls.

Group calling

Group calling allows participants to broadcast their presence to a particular “conference room”, upon which all participants already online will automatically add the new participant to the call. This results in a flexible “all-to-all” video conferencing solution.

For starting the sinchClient with the capability of making a group call, the capability “multiCall” must be set.

var sinchClient = new SinchClient({applicationKey: '...', capabilities: {calling: true, video: true, multiCall: true}}); // Notice the multiCall capability

When joining a particular group and acting on the incoming media streams from other participants, the Sinch JS SDK will automatically take care of all call management, but you have to initiate the process and act on certain callbacks in order to connect incoming media streams to the relevant HTML elements.

var callClient = sinchClient.getCallClient();

sinchClient.start({username: "<username>", password: "<password>"}).then(function() { // After the client is started, place the call
    var groupCall = callClient.callGroup("<name_of_group>");

    groupCall.addEventListener({
        onGroupRemoteCallAdded: function(call) { // Called when a remote participant stream is ready
            $('video#other').attr('src', call.incomingStreamURL);
        },
        onGroupLocalMediaAdded: function(stream) { // Called when the local media stream is ready (optional)
            $('video#me').attr('src', window.URL.createObjectURL(stream));
        },
        onGroupRemoteCallRemoved: function(call) { // Called when a remote participant has left and the stream needs to be removed from the HTML element
            $('video#other').attr('src', (remoteCalls[index] || {}).incomingStreamURL || '');
        },
    });
});

In this example, the group call is initiated after the client is started. A number of listeners was added in order to connect the incoming remote media streams (first callback), connect the local media stream and also manage lost participants. When the callGroup method is called, the callClient will immediatley start communication with other participants on the specified Channel in order to establish active video calls.

Instant Messaging

The MessageClient is the entry point to Instant Messaging functionality in the Sinch SDK.

Messages are sent and incoming messages are received through the MessageClient. An instance of MessageClient is owned by an instance of SinchClient and retrieved using sinchClient.getMessageClient(). Instant messaging is not enabled by default. In order to enable instant messaging, pass messaging: true in the list of capabilities when instantiating SinchClient.

Here is an example for how to set up the sinchClient, messageClient and add listeners for incoming messages and delivered messages.

var sinchClient = new SinchClient({
    applicationKey: '<application_key>',
    capabilities: {messaging: true},
});

var messageClient = sinchClient.getMessageClient();

var myListenerObj = {
    onMessageDelivered: function(messageDeliveryInfo) {
        // Handle message delivery notification
    },
    onIncomingMessage: function(message) {
        // Handle incoming message
    }
};

messageClient.addEventListener(myListenerObj);

Note: The getMessageClient() requires a sinchClient with the messaging capability set to true

Send a message

Sending a message with the Sinch SDK is easy. First, get hold of a MessageClient instance for a particular SinchClient instance. This can be done by calling the method getMessageClient(). Then use this instance to create a new Message object. This object can then be sent using send() in your MessageClient instance.

// Get the messageClient
var messageClient = sinchClient.getMessageClient(); 

// Create a new Message
var message = messageClient.newMessage('Alice', 'Hello World!');

// Send it
messageClient.send(message);

This example will send ‘Hello World’ to the user with username ‘Alice’.

Message sent success or failure

The send method returns a promise which can be used to chain a method when message was sent, this is specified using .then(). You can also supply two callbacks, one to be invoked on success and one for error.

// Create a new Message
var message = messageClient.newMessage('Alice', 'Hello World!');

// Success and fail handlers
var handleSuccess = function() {...};
var handleFail = function() {...};

// Alt 1: Send it with success and fail handler
messageClient.send(message, handleSuccess, handleFail)

// Alt 2: Send it and append handlers using the promise returned
messageClient.send(message)
    .then(handleSuccess)
    .then(some_other_success) 
    .fail(handleFail);

Note: If both callbacks and promises are used, the execution order is for callbacks to be executed first, followed by the methods in the promise-chain, specified using .then()

Delivery receipt

When a client receives a message, it sends an acknowledgement indicating which message was received. You can listen to these delivery receipts and take suitable action, for example, displaying which users have read a particular message.

All delivery receipts are sent to all onMessageDelivered listeners in the array of listeners managed by messageClient. In order to add your own listener, use the addEventListener() method in your messageClient.

// Retrieve messageClient for a particular sinchClient
var messageClient = sinchClient.getMessageClient();

// Define custom event listener
var myEventListener = {
    onMessageDelivered: function(messageDeliveryInfo) {
        // Perform action on message
        console.log(messageDeliveryInfo);
    },
    ...
}

// Add event listener
messageClient.addEventListener(myEventListener);

Note: If a recipient is online on one or multiple devices, the delivery report listener will only be called once on the first delivery receipt.

In order to remove a specific event listener, use the method removeEventListener()

// Define a custom event listener object
var myEventListener = {...};

// Add listener object
messageClient.addEventlistener(myEventListener);

// Remove listener object
messageClient.removeEventListener(myEventListener); 

Note: Several event listeners can be added, and they will be executed in the order which they were added.

Receive a message

In order to receive messages, SinchClient must be instantiated either with configuration option supportActiveConnection set to true or by invoking startActiveConnection after your SinchClient object has successfully started.

var sinchClient = new SinchClient({
    applicationKey: '<application_key>',
    capabilities: {messaging: true},
    supportActiveConnection: true,
});

All incoming messages are sent to all onIncomingMessage listeners in the array of listeners managed by an instance of MessageClient. In order to add one or more of your own listeners, use the addEventListener() method on a particular MessageClient instance.

// Retrieve messageClient for a particular sinchClient
var messageClient = sinchClient.getMessageClient();

// Define custom event listener
var myEventListener = {
    onIncomingMessage: function(message) {
        // Perform action on message
        console.log(message);
    },
    ...
}

// Add event listener to an array
messageClient.addEventListener(myEventListener);

In order to remove an event listener, use the method removeEventListener()

// Define a custom event listener object
var myEventListener = {...};

// Add this listener object
messageClient.addEventlistener(myEventListener);

// Remove this listener object
messageClient.removeEventListener(myEventListener); 

Note: Several event listeners can be added, they will be executed in the order which they where added.

Send a message to multiple recipients

When creating a new message, it’s possible to define multiple recipients by giving an array of recipients instead of a username string or identity object.

// Retrieve messageClient for particular sinchClient
var messageClient = sinchClient.getMessageClient();

// Create a new message for multiple recipients
var message = messageClient.newMessage(['Alice', 'Bob'], 'Hello Alice and Bob');

// Send message
messageClient.send(message); 

Both user ‘Alice’ and ‘Bob’ will receive the message. The success callback will only be called once, but there will be multiple delivery receipt listener callbacks, one for each recipient.

In order to send to multiple recipients with alternative identities, such as e-mail or phone number, supply an array of objects instead of an array with usernames.

// Retrieve messageClient for particular sinchClient
var messageClient = sinchClient.getMessageClient();

// Create a new message for multiple recipients, using number as their identity
var message = messageClient.newMessage([{number: 123456}, {number: 654321}], 'Hello Alice and Bob');

// Send message
messageClient.send(message); 

This will send the same “Hello World” message to the users identified by the numbers 123456 and 654321 respectivley.

Receiving recipient status updates for multi-recipient messages

The recipient’s state transition to delivered for the message is communicated back using the same listener as in the single recipient case. The listener’s callbacks are triggered for every recipient and only, at most, once per recipient.

Push Notifications

Push notifications are not yet implemented in the Sinch Javascript SDK.

Authentication

Authentication by your backend

It is possible to integrate Sinch with your existing user management solution. With this method, you get full control of your user database and can authenticate users in whichever way you see best fit; it may even be a third party solution.

This solution requires you to generate an authentication ticket using your application key and application secret on your Application Server. See the Reference Documentation for more information about generating this ticket.

The authentication ticket is then sent to Sinch, using the .start() method in the SinchClient instance. The ticket is exchanged into a Sinch session, and the rest of the process is identical to when Sinch manages your users.

Note: Included with the Sinch JS SDK are samples for getting you started with the integration of your authentication scheme with Sinch.

Figure 2. Authentication Supported by Partner Backend
Figure 2. Authentication Supported by Partner Backend

This method, where you authenticate users with your backend, may look like this:

var sinchClient = new SinchClient({
        applicationKey: 'MY_APPLICATION_KEY',
        capabilities: {messaging: true},
    });

// This jQuery call is just an example how you might authenticate users and pass the ticket to Sinch.
$.post('https://example.com/auth',
    {username: 'alice', password: 'somethingSecure'},
    function(authTicket) {
        sinchClient.start(authTicket)
            .then(function() {
                // Handle successful start, like showing the UI
            })
            .fail(function(error) {
                // Handle Sinch error
            });
    }, 
    function(error) {
        // Handle application server error
    });

This code will first instantiate the sinchClient with your application key. In this example, jQuery is used to perform an ajax request to your application server for authenticating the user Alice. jQuery will parse the json object and pass it to sinchClient.start().

When sinchClient.start() has successfully started the client, the success callback is executed, which may display the UI, or enable some buttons, or other actions you now want to take.

Authentication by Sinch

The Sinch JavaScript SDK allows for an easy authentication process requiring no backend, in order to get started quickly. Note however that we do not recommend to use this authentication model when launching your app live since you have no control over user creation. When going live, Sinch JS authentication can be disabled in the “App setting” section within the Dashboard.

Sinch JS authentication involves authenticating end-users by passing a user identity and password to sinchClient.start() when starting Sinch. In this scenario only the application key is needed; the application secret is not used and the authentication of individual users will be managed by us based on supplied user identity and password.

Figure 1. Authentication Supported by Sinch
Figure 1. Authentication Supported by Sinch

Authentication using this method is very straight forward, as you only have to make one method call. The Sinch SDK will take care of the rest under the hood. Implementing Sinch user authentication in your app may look something like this:

var sinchClient = new SinchClient({
        applicationKey: 'MY_APPLICATION_KEY',
        capabilities: {messaging: true},
    });

sinchClient.start({username: 'alice', password: 'somethingSecure'})
    .then(function() {
        // Perform actions to do when authenticated, such as displaying user interface
    });

This code will instantiate SinchClient, and will start the client using the username ‘Alice’.

User registration

Note: This is applicable only if you opted for Sinch JS Authentication.

In order to register new users there’s an SDK method called sinchClient.newUser(). This method can be used to create a new user and will return an authentication ticket which you can use to start a new sinchClient for the newly created users. This enables a great user experience, since the user does not have to create the account first and then login, and it’s all a smooth process.

Note: Username must be at least 4 characters in length.

The code for creating a new user and starting a sinchClient for this user may look like this:

var sinchClient = new SinchClient({
    applicationKey: 'MY_APPLICATION_KEY',
    capabilities: {messaging: true},
});

var handleSuccess = function() {...};
var handleFail = function() {...};

var signUpObject = {username: 'Alice', email: "alice@example.com", password: 'somethingSecure'};

sinchClient.newUser(signUpObject)
    .then(sinchClient.start.bind(sinchClient))
    .then(handleSuccess)
    .fail(handleFail);

Here we will try to create a new user using our sinchClient, the signUpObject must contain at least one identity, such as username, and the desired password. It may fail, in which case the method specified in .fail() will be called. A typical error is when a user is already existing with the same identity.

Note: Other valid identities include email or number.

After the new user is created, this code will proceed with executing the next method in the chain, which is starting the sinch client. The input parameter will be the output of newUser, which is an object with the authentication ticket. Finally, when the sinchClient is started, the handleSuccess method is called, which may do things like storing the session and displaying the user interface.

Note: Users created using the native SDK will have no password set, and can not be used with Sinch Authentication in the JS SDK. In scenarios where you need web authentication of users created using the native SDK, we recommend disabling Sinch authentication and instead integrate authentication with your custom backend.

Session Management

Between each page view, page reload or visit to the website, the current session is lost. Often there is an interest in re-using the same session and not forcing the end-user to re-authenticate. This can be solved by passing a session object into sinchClient.start(), and if the session is valid it will resume and you don’t have to prompt the user for any sign in. If it fails, you should fall back to whatever authentication method you’d like to use.

In order to be able to restore a session, it’s first required to save it on successful login.

Saving a session

If you’d like to save the session after authentication, the code may look something like this:

var sinchClient = new SinchClient({
        applicationKey: 'MY_APPLICATION_KEY',
        capabilities: {messaging: true},
    });

sinchClient.start({username: 'alice', password: 'somethingSecure'})
    then(function() {
        localStorage['sinchSession-' + sinchClient.applicationKey] = JSON.stringify(sinchClient.getSession());
    });

This code will start a sinchClient, authenticate using Sinch authentication and on success store the session in localStorage.

Note: In the future, Sinch may handle this for you.

Resuming a session

Next time the same visitor come back to the website, it’s nice if we can resume the same session. If we assume we have a saved session object, similar to the example above, we can resume it by passing the sessionObject to sinchClient.start().

Figure 3. Resume authenticated session
Figure 3. Resume authenticated session

In this case the code may look something like this:

//Parse the saved session object
var sessionObj = JSON.parse(localStorage['sinchSession-' + sinchClient.applicationKey] || '{}');

//If there is a valid session object
if(sessionObj.userId) {
    sinchClient.start(sessionObj)
        .then(handleStartSuccess)
        .fail(showLoginUI); //On failure, the session was not valid => user must re-login
}
else {
    showLoginUI(); //There is no session => user must login
}

The session object can be stored in any secure way you see best fit, for example in the browser localStorage as shown above. The session object can be retrieved from sinchClient using the sinchClient.getSession() method after a successful call to sinchClient.start().

See the Sample IM app for an example on working with sessions.

Miscellaneous

Restrictions on User IDs

User IDs can only contain characters in the printable ASCII character set. That is:

!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~

User IDs must not be longer than 40 characters.

Encryption export regulations

Please check the Summary of U.S. Export Controls Applicable to Commercial Encryption Products and ensure that the application is registered for the Encryption Regulations, if applicable. It can be found under this link.

Statistics

The Sinch SDK client uploads statistics to the Sinch servers at the end of a call, a call failure, or similar event. The statistics are used for monitoring of network status, call quality, and other aspects regarding the general quality of the service.

Some of the information is not anonymous and may be associated with the User ID call participants.

The statistics upload is done by the client in the background.