Server-Side Session and Token Management

Before you deploy anything, it helps to make the backend contract clear.

This module focuses on what the frontend will rely on and why stable session/token behavior matters.

For full context around this flow, see Server Essentials and Media & UI Basics.

Why this matters now

Your frontend exercise is much easier once backend behavior is predictable.

The goal here is to understand the lifecycle behind session/token creation.

Backend contract in one minute

Use this as the reference shape:

// routes/index.js

async function createSession(response, roomName, sessionProperties = {}, role = 'moderator') {
  let sessionId;
  let token;
  console.log(`Creating ${role} creds for ${roomName}`);

  if (roomToSessionIdDictionary[roomName]) {
    sessionId = roomToSessionIdDictionary[roomName];
    // generate token for user
    token = vonage.video.generateClientToken(sessionId, { role })
    response.setHeader('Content-Type', 'application/json');
    response.send({
      applicationId: appId,
      sessionId: sessionId,
      token: token
    });
  } else {
    try {
      // Create the session
      const session = await vonage.video.createSession(sessionProperties);
      roomToSessionIdDictionary[roomName] = session.sessionId;

      // generate token for user
      token = vonage.video.generateClientToken(session.sessionId, { role });
      response.setHeader('Content-Type', 'application/json');
      response.send({
        applicationId: appId,
        sessionId: session.sessionId,
        token: token
      });
    } catch(error) {
      console.error("Error creating session: ", error);
      response.status(500).send({ error: 'createSession error:' + error });
    }
  }
}

Notes that prevent integration drift

  • Sessions are cached in memory to keep everyone in the same room on subsequent requests.
  • vonage.video.createSession() talks to the Video API and provisions a media router if one does not exist yet.
  • vonage.video.generateClientToken() produces a JWT that includes role information (here we default to moderator so the user can control archives later).

The handler returns the Application ID, Session ID, and token back to the browser so it can initialize the SDK.

Quick check before backend deployment

  • You can explain what the frontend expects from /session.
  • You know which values are generated server-side versus supplied by client config.
  • You have a clear target for the Deploy the Backend exercise.