Suggestions

close search

Connection Token Creation — Node.js

In order to authenticate a user connecting to an OpenTok session, a client must connect using a token (see this overview).

The following Node.js code shows how to generate a token using the OpenTok Node.js server-side library:

// Set the following constants with the API key and API secret
// that you receive when you sign up to use the OpenTok API:
var opentok = new OpenTok(API_KEY, API_SECRET);

//Generate a basic session. Or you could use an existing session ID.
var sessionId;
opentok.createSession({}, function(error, session) {
  if (error) {
    console.log("Error creating session:", error)
  } else {
    sessionId = session.sessionId;
    console.log("Session ID: " + sessionId);
  }
});

var token = opentok.generateToken(sessionId);

Calling the generateToken() method returns a string. This string is the token.

The following Node.js code shows how to obtain a token that has a role of "publisher" and that has a connection metadata string:

// Set the following constants with the API key and API secret
// that you receive when you sign up to use the OpenTok API:
var opentok = new OpenTok(API_KEY, API_SECRET);

//Generate a basic session. Or you could use an existing session ID.
var sessionId;
var token
opentok.createSession({}, function(error, session) {
  if (error) {
    console.log("Error creating session:", error)
  } else {
    sessionId = session.sessionId;
    console.log("Session ID: " + sessionId);
    //  Use the role value appropriate for the user:
    var tokenOptions = {};
    tokenOptions.role = "publisher";
    tokenOptions.data = "username=bob";

    // Generate a token.
    token = opentok.generateToken(sessionId, tokenOptions);
    console.log(token);
  }
});

}

The method takes the following arguments: