Skip to content

Session Setup ​

A session is an authenticated connection between your client app and the Vonage API. Your backend issues a JWT, and the Client SDK uses that JWT in createSession().

Session model ​

  • Vonage API controls session lifecycle.
  • The Client SDK does not mint JWTs and does not manage token issuance.
  • Your backend remains the source of truth for identity and access policy.

Authentication flow ​

Backend JWT minting ​

INFO

The example below illustrates the required JWT structure. Your actual implementation will vary based on your backend language and framework.

JWTs must be generated on your server. The exact implementation is app-specific.

const privateKeyPem =
  '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----';

const payload: GuideJwtPayload = {
  application_id: applicationId,
  sub: userName,
  acl: {
    paths: {
      '/*/users/**': {},
      '/*/conversations/**': {},
      '/*/sessions/**': {},
      '/*/devices/**': {},
      '/*/image/**': {},
      '/*/media/**': {},
      '/*/applications/**': {}
    }
  },
  exp: Math.floor(Date.now() / 1000) + 60 * 60
};

const jwt = signJwt(payload, privateKeyPem);
console.log(jwt);

Create a session ​

val client = VoiceClient(ctx)

val config = VGClientConfig(VGConfigRegion.EU)
client.setConfig(config)

client.createSession(jwt) { error, sessionId ->
    if (error != null) {
        println("Failed to create session: $error")
        return@createSession
    }

    println("Session created: $sessionId")
}

Region ​

Yes, the region affects calls. It selects the Vonage hosts the SDK talks to:

RegionAPI hostWebSocket host
US (default)https://api-us.vonage.comhttps://ws-us.vonage.com
EUhttps://api-eu.vonage.comhttps://ws-eu.vonage.com
APhttps://api-ap.vonage.comhttps://ws-ap.vonage.com
  • Outbound in-app calls are processed in the region of the endpoint the SDK uses.
  • Inbound phone (PSTN) and SIP calls are processed in the region set in your application's Voice settings in the Vonage dashboard.
  • The default is US. Users and their data belong to one region and are not visible from another, so the SDK cannot pick a region for you.

Use the same region in all three places: the SDK configuration, your application's Voice region, and the API region where you created your users. The SDK does not choose where call media is anchored; that is decided by Vonage. See Vonage Voice API regions.

Set the region before calling createSession:


val config = VGClientConfig(VGConfigRegion.EU)
config.apiUrl = "https://api.example.com"
config.websocketUrl = "https://ws.example.com"
config.enableWebsocketInvites = true
config.rtcStatsTelemetry = true
config.autoReconnectMedia = false
config.enableNoiseSuppression = true
client.setConfig(config)

Session lifecycle ​

Call createSession once ​

Call createSession once, after login. From then on the SDK keeps the session connected. You do not need to call it again when the app returns to the foreground, when a push arrives, or after the network drops.

The session lasts until the JWT's exp claim. The SDK has no session TTL of its own. To keep the session past exp, call refreshSession with a new JWT before it expires.

Automatic reconnection ​

When the connection to Vonage drops, or the app was frozen in the background, the SDK resumes the same session on its own:

  • It fires onReconnecting at once.
  • It retries after 1, 2 and 4 seconds, then every 5 seconds, with jitter. On the web it also retries at once when the browser comes back online.
  • It fires onReconnection once Vonage has confirmed the session on the new connection.

It keeps trying for up to 15 minutes after the connection was lost. That is how long Vonage keeps a disconnected session. After that, the session has ended and onSessionError fires.

After a freeze (iOS suspension, Android Doze, a sleeping laptop, a frozen browser tab) the connection can look open while the server has long stopped hearing it. If nothing has been heard from Vonage for more than 45 seconds, the SDK replaces the connection as soon as the app runs again: on the next read of connectionStatus, the next serverCall or answer, or the SDK's own periodic check. If more than 15 minutes have passed, it ends the session straight away instead.

Missed events ​

Vonage replays events missed during a drop for only about 30 seconds, not 15 minutes. To cover the rest of the gap, the SDK re-reads every call and pending invite it holds over REST after each reconnect:

  • A call that ended while the device was offline fires onCallHangup with its real reason. The REST response has no audio counters, so every callQuality field is 0.
  • A call still being set up by serverCall completes, keeps waiting, or ends with the dialled party's outcome.
  • An invite that was cancelled, or answered or rejected on another device, fires onCallInviteCancel.

Connection status ​

connectionStatus tells you whether the client can place and receive calls right now. Reading it first checks that Vonage has been heard recently, so a read right after the app resumes or is woken by a push is accurate.

StatusMeaningWhat you can do
DisconnectedNo session, or the session has ended.Call createSession. serverCall, refreshSession and deleteSession fail with session:error:no-active-session.
ConnectingYour createSession is in progress, or the SDK is reattaching the session after a drop.During your own createSession, wait for its callback. While reattaching, place and answer calls as usual. refreshSession works.
ConnectedThe session is attached to a live connection.Everything.

A connection that dies silently while the app keeps running is noticed by the heartbeat: after about 4 seconds on iOS, and up to about 45 seconds on Android and the web.

When a push arrives:

  • Disconnected: call createSession with your stored JWT, then process the push. On iOS, process the push at once and create the session concurrently; see the iOS push guide.
  • Connecting because your own createSession is still running: wait for its callback, then process the push.
  • Connecting while the SDK reattaches, or Connected: process the push now. Do not call createSession.

When the session ends ​

onSessionError means the session cannot be resumed. connectionStatus is Disconnected and calls cannot be made or received until you create a new session.

ReasonWhat to do
TokenExpiredThe JWT expired. Get a new JWT from your backend, then call createSession.
TransportClosedThe connection could not be restored within 15 minutes, or Vonage ended the session. Call createSession again when the device is back online. The same JWT is fine if it has not expired.
PingTimeoutDeprecated. Never reported.

refreshSession ​

refreshSession only replaces the session's JWT. Call it before the current JWT's exp, for example a few minutes before it expires.

  • It is a REST request, so it also works while the SDK is reattaching. The reattach then uses the new JWT.
  • It does not reconnect or reattach anything. The SDK already does that on its own.
  • After onSessionError there is no session to refresh: it fails with session:error:no-active-session. Call createSession instead.

Calling createSession again ​

createSession while a session exists replaces it: the SDK deletes the current session, then creates the new one. It does not fail.

WARNING

Do not call createSession on every foreground or every push. It throws away a live session, and calls in progress on it fail. Check connectionStatus and call createSession only when it is Disconnected.

If the app process was restarted, you can pass the stored session ID to createSession to reattach to it within the 15-minute window. See Recover pending call invites.

Handling errors ​

createSession can fail for several reasons. Always handle the error callback:

kotlin
client.createSession(token) { error, sessionId ->
    if (error != null) {
        when {
            error.message?.contains("token") == true ->
                // Invalid or expired JWT — request a new one from your backend
                println("Token error: $error")
            else ->
                println("Session creation failed: $error")
        }
    } else {
        println("Session created: $sessionId")
    }
}

For a full list of possible error types, see Errors. For the cause of each error and what to do about it, see Troubleshooting.

Built with VitePress.