Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Twillio Access Tokens using Node JS

I'm developing an application that uses Twillios Programmable Video API.

I'm new to using Node JS, but the documentation has been fairly straightforward, however I still have a few questions.

Here's code I am referencing.

const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;

// Used when generating any kind of tokens
const twilioAccountSid = 'ACxxxxxxxxxx';
const twilioApiKey = 'SKxxxxxxxxxx';
const twilioApiSecret = 'xxxxxxxxxxxx';

const identity = 'user';

// Create Video Grant
const videoGrant = new VideoGrant({
room: 'cool room'
});

// Create an access token which we will sign and return to the client,
// containing the grant we just created
const token = new AccessToken(twilioAccountSid, twilioApiKey, twilioApiSecret);
token.addGrant(videoGrant);
token.identity = identity;

// Serialize the token to a JWT string
console.log(token.toJwt());

In this specific example provided by Twillio, the video grant which I assume is mandatory is explicitly referenced, however that would mean for this specific token generator, the users can only enter rooms of that name.

I was wondering if it was possible to reference the room before configuring the token. Something similar to how the identity is a variable that's entered into the function before the token is output.

In addition, are there any required dependencies or libraries when creating tokens outside of Twillios own function environment?

Any answers, suggestions, or references are greatly appreciated.

like image 780
Stefan Avatar asked Jul 18 '26 15:07

Stefan


1 Answers

Twilio developer evangelist here.

It is possible to supply the room name as a variable too. You might want to create a function that can take an identity and room name as arguments and returns an access token. Something like this:

const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;

// Used when generating any kind of tokens
const twilioAccountSid = 'ACxxxxxxxxxx';
const twilioApiKey = 'SKxxxxxxxxxx';
const twilioApiSecret = 'xxxxxxxxxxxx';


function generateToken(identity, roomName) {
  const videoGrant = new VideoGrant({
    room: roomName
  });
  const token = new AccessToken(twilioAccountSid, twilioApiKey, twilioApiSecret);
  token.addGrant(videoGrant);
  token.identity = identity;
  return token.toJwt();
}

Then you can use the function like:

const token = generateToken("Stefan", "StefansRoom");

Let me know if that helps at all.

like image 89
philnash Avatar answered Jul 20 '26 07:07

philnash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!