Skip to contentSkip to navigationSkip to topbar
On this page

Get Started with Twilio Video Part 1: Creating a server with Node/Express


This is the first part of a two-part tutorial for creating a video web application with a Node/Express backend and a JavaScript frontend. In this section, you'll set up a backend server that creates free Twilio WebRTC Go video rooms and generates Access Tokens for video room participants. In part two, you'll create the frontend side of the application, where participants can join a video room and share their video and audio with other participants.

At the end of this full tutorial, you'll have a web application that allows you to join a two-person video room and video chat with another person.

If you have already completed the backend section of this tutorial, jump over to Part Two. Otherwise, let's get going!


Setup

setup page anchor

Requirements

requirements page anchor

Create the project directory

create-the-project-directory page anchor

Open a new terminal window and navigate to the directory where you want your project to live. Then, create a project folder and change into this directory:

mkdir video_tutorial && cd video_tutorial

Collect account values and store them in a .env file

collect-account-values-and-store-them-in-a-env-file page anchor

To start, you'll need to collect a few values from the Twilio Console(link takes you to an external page) so that you can connect your application to Twilio. You will store these values in a .env file, and your server will read in these values.

Within the new project folder you created above, create a file called .env and open it in your preferred text editor.

The first value you'll need is your Account SID, which you can find in the Twilio Console(link takes you to an external page). Once you've gotten that value, store it in the .env file:

TWILIO_ACCOUNT_SID=<your account sid>

Create an API Key

create-an-api-key page anchor

Next, you'll need to create an API key. This is what you'll use to authenticate with Twilio when making API calls.

You can create an API key using the Twilio CLI, the REST API, or the Twilio Console(link takes you to an external page). This tutorial will show how to generate it via the Console.

To generate the API Key from the Twilio Console:

When you've created the key, you'll see the friendly name, type, key SID, and API key secret.

(warning)

Warning

Make sure to copy the secret now, because you'll only be able to see it once. When you leave this page, you won't be able to see the secret again.

Copy the API Key ID and the API Key Secret and store both values in the .env file.

1
TWILIO_ACCOUNT_SID=<your account sid>
2
TWILIO_API_KEY_SID=<key sid>
3
TWILIO_API_KEY_SECRET=<secret>

If you're using git for version control, make sure these credentials remain secure and out of version control. To do this, create a .gitignore file at the root of your project directory. In this file, you can list the files and directories that you want git to ignore from being tracked or committed.

Open the new .gitignore file in your code editor and add the .env file. While you're here, you can also add node_modules/, for the dependencies folder you'll install in the next step.

1
.env
2
node_modules/

Great! Now that you've stored those credentials and added the .env to .gitignore, you can move on to creating the Express server.

Install the dependencies

install-the-dependencies page anchor

First, set up a new Node.js project with a default package.json file by running the following command:

npm init --yes

Once you have your package.json file, you're ready to install the needed dependencies.

For this project, you will need the following packages:

Run the following command to install the dependencies:

npm install express twilio dotenv node-dev uuid

If you check your package.json file now, you'll notice that the packages above have been installed as dependencies.


You will need a server to generate Access Tokens (to grant participants permission to access a video room) and serve the frontend code that you'll build in Part Two of this tutorial. There are several options for creating web servers with Node.js, but this tutorial uses Express(link takes you to an external page).

This section walks through the general setup for a basic Express server. In the next section, you'll add the Twilio-specific code for creating video rooms.

First, create a new file called server.js at the root of the project directory. This will be the server file where you put all the core logic for your web server. Open that file in your text editor and copy and paste the following code into the file:

1
require("dotenv").config();
2
const { v4: uuidv4 } = require("uuid");
3
const AccessToken = require("twilio").jwt.AccessToken;
4
const VideoGrant = AccessToken.VideoGrant;
5
const express = require("express");
6
const app = express();
7
const port = 5000;
8
9
// use the Express JSON middleware
10
app.use(express.json());
11
12
13
// create the twilioClient
14
const twilioClient = require("twilio")(
15
process.env.TWILIO_API_KEY_SID,
16
process.env.TWILIO_API_KEY_SECRET,
17
{ accountSid: process.env.TWILIO_ACCOUNT_SID }
18
);
19
20
// Start the Express server
21
app.listen(port, () => {
22
console.log(`Express server running on port ${port}`);
23
});

This code pulls in the required dependencies for the server, loads the environment variables from your .env file, starts a new Express application, and sets the application to run on port 5000. It also creates a Twilio client with the Twilio Node helper library. You'll use this client to communicate with Twilio.

At the bottom of the code, you start the Express server on port 5000.

Now, open package.json in your code editor. Inside the scripts section, add a start script as shown below. You can replace the test script that was automatically generated by npm init --yes earlier:

1
"scripts": {
2
"start": "node-dev server.js"
3
},
4

To run the start script, return to your terminal window and run the following command:

1
npm start
2

Once you have done this, you should see the following log statement in your terminal window, letting you know that the Express server is running:

Express server running on port 5000

You'll use the twilioClient you created earlier in server.js, and write a function to create new video rooms.

In server.js, underneath where you created the twilioClient variable, paste in the following function:

1
const findOrCreateRoom = async (roomName) => {
2
try {
3
// see if the room exists already. If it doesn't, this will throw
4
// error 20404.
5
await twilioClient.video.rooms(roomName).fetch();
6
} catch (error) {
7
// the room was not found, so create it
8
if (error.code == 20404) {
9
await twilioClient.video.rooms.create({
10
uniqueName: roomName,
11
type: "go",
12
});
13
} else {
14
// let other errors bubble up
15
throw error;
16
}
17
}
18
};

In the code above, you create a function called findOrCreateRoom, which takes in a room name and checks if an in-progress video room with that name already exists for your account. If that room doesn't exist, you'll get Error 20404, which will indicate that you should create the room.

This function will create the room as a WebRTC Go room (type: "go"), which is a free room that can have up to two participants.

Eventually, you'll use this function to allow a participant to specify a room to either create or join. In the next section, you'll write a function to create an Access Token for a participant.

Here's the full server.js code with the new find_or_create_room function:

1
require("dotenv").config();
2
const { v4: uuidv4 } = require("uuid");
3
const AccessToken = require("twilio").jwt.AccessToken;
4
const VideoGrant = AccessToken.VideoGrant;
5
const express = require("express");
6
const app = express();
7
const port = 5000;
8
9
// use the Express JSON middleware
10
app.use(express.json());
11
12
// create the twilioClient
13
const twilioClient = require("twilio")(
14
process.env.TWILIO_API_KEY_SID,
15
process.env.TWILIO_API_KEY_SECRET,
16
{ accountSid: process.env.TWILIO_ACCOUNT_SID }
17
);
18
19
const findOrCreateRoom = async (roomName) => {
20
try {
21
// see if the room exists already. If it doesn't, this will throw
22
// error 20404.
23
await twilioClient.video.rooms(roomName).fetch();
24
} catch (error) {
25
// the room was not found, so create it
26
if (error.code == 20404) {
27
await twilioClient.video.rooms.create({
28
uniqueName: roomName,
29
type: "go",
30
});
31
} else {
32
// let other errors bubble up
33
throw error;
34
}
35
}
36
};
37
38
// Start the Express server
39
app.listen(port, () => {
40
console.log(`Express server running on port ${port}`);
41
});

Generate an Access Token for a Participant

generate-an-access-token-for-a-participant page anchor

Now, you'll create a function that returns an Access Token for a participant. An Access Token gives a participant permission to join video rooms.

The Access Token will be in the JSON Web Token (JWT)(link takes you to an external page) standard. The Node Twilio helper library contains functions for creating and decoding these tokens in the JWT format.

Copy and paste the following getAccessToken function in server.js, under the findOrCreateRoom function:

1
const getAccessToken = (roomName) => {
2
// create an access token
3
const token = new AccessToken(
4
process.env.TWILIO_ACCOUNT_SID,
5
process.env.TWILIO_API_KEY_SID,
6
process.env.TWILIO_API_KEY_SECRET,
7
// generate a random unique identity for this participant
8
{ identity: uuidv4() }
9
);
10
// create a video grant for this specific room
11
const videoGrant = new VideoGrant({
12
room: roomName,
13
});
14
15
// add the video grant
16
token.addGrant(videoGrant);
17
// serialize the token and return it
18
return token.toJwt();
19
};

The function does the following:

  • Takes in a room name

  • Creates an Access Token (in JWT(link takes you to an external page) format)

    • Generates a unique string for a participant's identity (see note below about the participant identity requirement)
  • Creates a Video Grant

  • Adds it to the Access Token

  • Returns the token in serialized format

(information)

Info

The participant identity doesn't need to be a random string — it could be a value like an email, a user's name, or a user ID. However, it does need to be a unique value for the specific room. You cannot create more than one token for a given participant identity in a room.

The Video Grant is important to add to the token, because it is the piece that allows a participant to connect to video rooms. You can limit the participant's access to a particular video room (which the code above does), or you can generate a token with general access to video rooms.

If you were going to connect this application with other Twilio services, such as Twilio Sync or Twilio Conversations(link takes you to an external page), you could create additional Sync or Conversation grants and add them to this token to allow access to those services as well.

Here's the full server code with the added getAccessToken function:

1
require("dotenv").config();
2
const { v4: uuidv4 } = require("uuid");
3
const AccessToken = require("twilio").jwt.AccessToken;
4
const VideoGrant = AccessToken.VideoGrant;
5
const express = require("express");
6
const app = express();
7
const port = 5000;
8
9
// use the Express JSON middleware
10
app.use(express.json());
11
12
// create the twilioClient
13
const twilioClient = require("twilio")(
14
process.env.TWILIO_API_KEY_SID,
15
process.env.TWILIO_API_KEY_SECRET,
16
{ accountSid: process.env.TWILIO_ACCOUNT_SID }
17
);
18
19
const findOrCreateRoom = async (roomName) => {
20
try {
21
// see if the room exists already. If it doesn't, this will throw
22
// error 20404.
23
await twilioClient.video.rooms(roomName).fetch();
24
} catch (error) {
25
// the room was not found, so create it
26
if (error.code == 20404) {
27
await twilioClient.video.rooms.create({
28
uniqueName: roomName,
29
type: "go",
30
});
31
} else {
32
// let other errors bubble up
33
throw error;
34
}
35
}
36
};
37
38
const getAccessToken = (roomName) => {
39
// create an access token
40
const token = new AccessToken(
41
process.env.TWILIO_ACCOUNT_SID,
42
process.env.TWILIO_API_KEY_SID,
43
process.env.TWILIO_API_KEY_SECRET,
44
// generate a random unique identity for this participant
45
{ identity: uuidv4() }
46
);
47
// create a video grant for this specific room
48
const videoGrant = new VideoGrant({
49
room: roomName,
50
});
51
52
// add the video grant
53
token.addGrant(videoGrant);
54
// serialize the token and return it
55
return token.toJwt();
56
};
57
58
// Start the Express server
59
app.listen(port, () => {
60
console.log(`Express server running on port ${port}`);
61
});

Put it all together in a route

put-it-all-together-in-a-route page anchor

Next, you'll create a route called /join-room. In Part Two of this Tutorial, your frontend application will make a POST request to this /join-room route with a roomName in the body of the request.

Copy and paste the following code in server.js, underneath the route that returns "In progress!":

1
app.post("/join-room", async (req, res) => {
2
// return 400 if the request has an empty body or no roomName
3
if (!req.body || !req.body.roomName) {
4
return res.status(400).send("Must include roomName argument.");
5
}
6
const roomName = req.body.roomName;
7
// find or create a room with the given roomName
8
findOrCreateRoom(roomName);
9
// generate an Access Token for a participant in this room
10
const token = getAccessToken(roomName);
11
res.send({
12
token: token,
13
});
14
});

This route takes a POST request containing a JSON object with a room name, and then calls the find_or_create_room function and the get_access_token function. It returns the decoded Access Token, which is a JSON Web Token (JWT)(link takes you to an external page).

Here's the final server file with all of these pieces:

1
require("dotenv").config();
2
const { v4: uuidv4 } = require("uuid");
3
const AccessToken = require("twilio").jwt.AccessToken;
4
const VideoGrant = AccessToken.VideoGrant;
5
const express = require("express");
6
const app = express();
7
const port = 5000;
8
9
// use the Express JSON middleware
10
app.use(express.json());
11
12
// create the twilioClient
13
const twilioClient = require("twilio")(
14
process.env.TWILIO_API_KEY_SID,
15
process.env.TWILIO_API_KEY_SECRET,
16
{ accountSid: process.env.TWILIO_ACCOUNT_SID }
17
);
18
19
const findOrCreateRoom = async (roomName) => {
20
try {
21
// see if the room exists already. If it doesn't, this will throw
22
// error 20404.
23
await twilioClient.video.rooms(roomName).fetch();
24
} catch (error) {
25
// the room was not found, so create it
26
if (error.code == 20404) {
27
await twilioClient.video.rooms.create({
28
uniqueName: roomName,
29
type: "go",
30
});
31
} else {
32
// let other errors bubble up
33
throw error;
34
}
35
}
36
};
37
38
const getAccessToken = (roomName) => {
39
// create an access token
40
const token = new AccessToken(
41
process.env.TWILIO_ACCOUNT_SID,
42
process.env.TWILIO_API_KEY_SID,
43
process.env.TWILIO_API_KEY_SECRET,
44
// generate a random unique identity for this participant
45
{ identity: uuidv4() }
46
);
47
// create a video grant for this specific room
48
const videoGrant = new VideoGrant({
49
room: roomName,
50
});
51
52
// add the video grant
53
token.addGrant(videoGrant);
54
// serialize the token and return it
55
return token.toJwt();
56
};
57
58
app.post("/join-room", async (req, res) => {
59
// return 400 if the request has an empty body or no roomName
60
if (!req.body || !req.body.roomName) {
61
return res.status(400).send("Must include roomName argument.");
62
}
63
const roomName = req.body.roomName;
64
// find or create a room with the given roomName
65
findOrCreateRoom(roomName);
66
// generate an Access Token for a participant in this room
67
const token = getAccessToken(roomName);
68
res.send({
69
token: token,
70
});
71
});
72
73
// Start the Express server
74
app.listen(port, () => {
75
console.log(`Express server running on port ${port}`);
76
});

Test this new route by running the server (with the command npm start) and making a POST request to http://localhost:5000/join-room. You can use curl(link takes you to an external page), Postman(link takes you to an external page), HTTPie(link takes you to an external page), or another tool for making this request. To make the request using curl, run the following command in your terminal:

1
curl -X POST http://localhost:5000/join-room \
2
-H "Content-Type: application/json" \
3
--data '{"roomName": "test room!"}'

You should receive output similar to the output below:

1
{
2
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0..."
3
}

You can use the site jwt.io(link takes you to an external page) to inspect the token you received and see the different components that make up the Access Token. If you paste the token you received into the jwt.io debugger, it will decode the token and show you what the token includes. You should see that it contains a video grant for the specific room you created. The token will also include fields with other information you provided:

  • iss: your TWILIO_API_KEY_SID
  • sub: your TWILIO_ACCOUNT_SID
  • identity: the randomly generated uuid for the participant's identity

You now have a working backend server that will create video rooms and generate Access Tokens! You're done with this section of the tutorial and can move on to Part Two, where you'll create the frontend for this web app.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.