Get Started with Twilio Video Part 1: Creating a server with Node or Express
This is the first part of a two-part tutorial for creating a video web application with a Node or Express backend and a JavaScript frontend. In this section, you'll set up a backend server that creates Twilio Group 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've already completed the backend section of this tutorial, jump over to Part Two.
- Node.js (most recent LTS version) and npm installed on your machine
- A free Twilio account. Sign up for a free account or log into an existing account.
- VS Code. You can use any code editor you like, but this tutorial uses VS Code, so the instructions will be specific to that editor.
Open a terminal window and go 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
To start, you'll need to collect a few values from the Twilio Console so that you can connect your application to Twilio. You'll store these values in a .env file, and your server will read in these values.
Within the project folder you created above, create a file called .env.
The first value you'll need is your Account SID, which you can find in the Twilio Console. Once you've gotten that value, store it in the .env file:
TWILIO_ACCOUNT_SID=<your account sid>
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. This tutorial will show how to generate it via the Console.
To generate the API Key from the Twilio Console:
- Go to the API keys section of the Twilio Console and click "Create API key."
- Give the key a friendly name, such as "First Video Project."
- Choose "United States (US1)" for the Region. Keys created outside the United States (US1) region won't work.
- Choose "Standard" for the key type.
- Click "Create API Key".
When you've created the key, you'll see the friendly name, type, key SID, and API key secret.
Warning
Make sure to copy the secret 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.
1TWILIO_ACCOUNT_SID=<your account sid>2TWILIO_API_KEY_SID=<key sid>3TWILIO_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 .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.env2node_modules/
After you've stored those credentials and added the .env to .gitignore, you can move on to creating the Express server.
First, set up a Node.js project with a default package.json file by running the following command:
npm init --yes
Once you've got your package.json file, you're ready to install the needed dependencies.
For this project, you'll need the following packages:
- Express, a Node.js framework
- Twilio Node SDK, to use the Twilio APIs
- dotenv, to load the environment variables from a
.envfile into your application - node-dev, to restart the Node process when you modify a file
- uuid, to generate random values for participant identities
Run the following command to install the dependencies:
npm install express twilio dotenv node-dev uuid
If you check your package.json file, you'll notice that the packages above have been installed as dependencies.
After installing the dependencies, you need to make a few modifications to your package.json file to ensure the project works correctly with modern JavaScript modules.
Open package.json in your text editor and update it to match the following configuration:
1{2"name": "video_tutorial",3"version": "1.0.0",4"description": "",5"main": "index.js",6"type": "module",7"scripts": {8"start": "node-dev server.js"9},10"keywords": [],11"author": "",12"license": "ISC",13"dependencies": {14"dotenv": "^17.3.1",15"express": "^5.2.1",16"node-dev": "^8.0.0",17"twilio": "^5.12.2",18"uuid": "^13.0.0"19}20}
The key changes to note are:
- Adding
"type": "module"to use ES6 module syntax - Adding a
startscript in thescriptssection that usesnode-devto run the server with reloading when files change
You'll need a server to generate Access Tokens to grant participants permission to access a video room. The server will also 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.
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 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:
1import dotenv from "dotenv";2import { v4 as uuidv4 } from "uuid";3import twilio from "twilio";4import express from "express";56dotenv.config();78const AccessToken = twilio.jwt.AccessToken;9const VideoGrant = AccessToken.VideoGrant;10const app = express();11const port = 5000;1213// use the Express JSON middleware14app.use(express.json());1516// create the twilioClient17const twilioClient = twilio(18process.env.TWILIO_API_KEY_SID,19process.env.TWILIO_API_KEY_SECRET,20{ accountSid: process.env.TWILIO_ACCOUNT_SID }21);2223// Start the Express server24app.listen(port, () => {25console.log(`Express server running on port ${port}`);26});
This code pulls in the required dependencies for the server, loads the environment variables from your .env file, and starts an Express application. The application runs on port 5000. This code also creates a Twilio client with the Twilio Node SDK. You'll use this client to communicate with Twilio.
At the bottom of the code, you start the Express server on port 5000.
To run the server using the start script you configured earlier in package.json, return to your terminal window and run the following command:
1npm start2
After the server starts, you'll see the following log statement in your terminal window:
Express server running on port 5000
You'll use the twilioClient you created earlier in server.js and write a function to create video rooms.
In server.js, underneath where you created the twilioClient variable, paste in the following function:
1const findOrCreateRoom = async (roomName) => {2try {3// see if the room exists already. If it doesn't, this will throw4// error 20404.5await twilioClient.video.v1.rooms(roomName).fetch();6} catch (error) {7// the room was not found, so create it8if (error.code == 20404) {9await twilioClient.video.v1.rooms.create({10uniqueName: roomName,11type: "group",12});13} else {14// let other errors bubble up15throw error;16}17}18};
In the code above, you create a function called findOrCreateRoom. This function 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 indicates that you need to create the room.
This function will create the room as a Group room (type: "group"). Group rooms use Twilio cloud infrastructure to relay media between participants, which provides better quality and scalability than peer-to-peer connections.
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 findOrCreateRoom function:
1import dotenv from "dotenv";2import { v4 as uuidv4 } from "uuid";3import twilio from "twilio";4import express from "express";56dotenv.config();78const AccessToken = twilio.jwt.AccessToken;9const VideoGrant = AccessToken.VideoGrant;10const app = express();11const port = 5000;1213// use the Express JSON middleware14app.use(express.json());1516// create the twilioClient17const twilioClient = twilio(18process.env.TWILIO_API_KEY_SID,19process.env.TWILIO_API_KEY_SECRET,20{ accountSid: process.env.TWILIO_ACCOUNT_SID }21);2223const findOrCreateRoom = async (roomName) => {24try {25// see if the room exists already. If it doesn't, this will throw26// error 20404.27await twilioClient.video.v1.rooms(roomName).fetch();28} catch (error) {29// the room was not found, so create it30if (error.code == 20404) {31await twilioClient.video.v1.rooms.create({32uniqueName: roomName,33type: "group",34});35} else {36// let other errors bubble up37throw error;38}39}40};4142// Start the Express server43app.listen(port, () => {44console.log(`Express server running on port ${port}`);45});
Next, 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) standard. The Node Twilio SDK 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:
1const getAccessToken = (roomName) => {2// create an access token3const token = new AccessToken(4process.env.TWILIO_ACCOUNT_SID,5process.env.TWILIO_API_KEY_SID,6process.env.TWILIO_API_KEY_SECRET,7// generate a random unique identity for this participant8{ identity: uuidv4() }9);10// create a video grant for this specific room11const videoGrant = new VideoGrant({12room: roomName,13});1415// add the video grant16token.addGrant(videoGrant);17// serialize the token and return it18return token.toJwt();19};
The function does the following:
-
Takes in a room name
-
Creates an Access Token (in JWT 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
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, each participant currently connected to a room must have a unique identity. If a second participant joins with the same identity as someone already in the room, Twilio will disconnect the first participant.
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, you could create additional grants. For example, you could add Sync or Conversation grants to allow access to Twilio Sync or Twilio Conversations.
Here's the full server code with the added getAccessToken function:
1import dotenv from "dotenv";2import { v4 as uuidv4 } from "uuid";3import twilio from "twilio";4import express from "express";56dotenv.config();78const AccessToken = twilio.jwt.AccessToken;9const VideoGrant = AccessToken.VideoGrant;10const app = express();11const port = 5000;1213// use the Express JSON middleware14app.use(express.json());1516// create the twilioClient17const twilioClient = twilio(18process.env.TWILIO_API_KEY_SID,19process.env.TWILIO_API_KEY_SECRET,20{ accountSid: process.env.TWILIO_ACCOUNT_SID }21);2223const findOrCreateRoom = async (roomName) => {24try {25// see if the room exists already. If it doesn't, this will throw26// error 20404.27await twilioClient.video.v1.rooms(roomName).fetch();28} catch (error) {29// the room was not found, so create it30if (error.code == 20404) {31await twilioClient.video.v1.rooms.create({32uniqueName: roomName,33type: "group",34});35} else {36// let other errors bubble up37throw error;38}39}40};4142const getAccessToken = (roomName) => {43// create an access token44const token = new AccessToken(45process.env.TWILIO_ACCOUNT_SID,46process.env.TWILIO_API_KEY_SID,47process.env.TWILIO_API_KEY_SECRET,48// generate a random unique identity for this participant49{ identity: uuidv4() }50);51// create a video grant for this specific room52const videoGrant = new VideoGrant({53room: roomName,54});5556// add the video grant57token.addGrant(videoGrant);58// serialize the token and return it59return token.toJwt();60};6162// Start the Express server63app.listen(port, () => {64console.log(`Express server running on port ${port}`);65});
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 getAccessToken function:
1app.post("/join-room", async (req, res) => {2try {3// return 400 if the request has an empty body or no roomName4if (!req.body || !req.body.roomName) {5return res.status(400).send("Must include roomName argument.");6}7const roomName = req.body.roomName;8// find or create a room with the given roomName9await findOrCreateRoom(roomName);10// generate an Access Token for a participant in this room11const token = getAccessToken(roomName);12res.send({13token: token,14});15} catch (error) {16console.error("Error in /join-room:", error);17res.status(500).send({18error: error.message,19});20}21});
This route takes a POST request containing a JSON object with a room name, and then calls the findOrCreateRoom function and the getAccessToken function. It returns the serialized Access Token, which is a JSON Web Token (JWT). The route includes error handling to catch and return any errors that occur during room creation or token generation.
Here's the final server file with all of these pieces:
1import dotenv from "dotenv";2import { v4 as uuidv4 } from "uuid";3import twilio from "twilio";4import express from "express";56dotenv.config();78const AccessToken = twilio.jwt.AccessToken;9const VideoGrant = AccessToken.VideoGrant;10const app = express();11const port = 5000;1213// use the Express JSON middleware14app.use(express.json());1516// create the twilioClient17const twilioClient = twilio(18process.env.TWILIO_API_KEY_SID,19process.env.TWILIO_API_KEY_SECRET,20{ accountSid: process.env.TWILIO_ACCOUNT_SID }21);2223const findOrCreateRoom = async (roomName) => {24try {25// see if the room exists already. If it doesn't, this will throw26// error 20404.27await twilioClient.video.v1.rooms(roomName).fetch();28} catch (error) {29// the room was not found, so create it30if (error.code == 20404) {31await twilioClient.video.v1.rooms.create({32uniqueName: roomName,33type: "group",34});35} else {36// let other errors bubble up37throw error;38}39}40};4142const getAccessToken = (roomName) => {43// create an access token44const token = new AccessToken(45process.env.TWILIO_ACCOUNT_SID,46process.env.TWILIO_API_KEY_SID,47process.env.TWILIO_API_KEY_SECRET,48// generate a random unique identity for this participant49{ identity: uuidv4() }50);51// create a video grant for this specific room52const videoGrant = new VideoGrant({53room: roomName,54});55// Note: You can generate multiple Access Tokens with the same identity.56// The identity must be unique among participants currently connected to the room.57// If a second participant joins with the same identity, Twilio disconnects the first58// participant (see Error 53205).59// add the video grant60token.addGrant(videoGrant);61// serialize the token and return it62return token.toJwt();63};6465app.post("/join-room", async (req, res) => {66try {67// return 400 if the request has an empty body or no roomName68if (!req.body || !req.body.roomName) {69return res.status(400).send("Must include roomName argument.");70}71const roomName = req.body.roomName;72// find or create a room with the given roomName73await findOrCreateRoom(roomName);74// generate an Access Token for a participant in this room75const token = getAccessToken(roomName);76res.send({77token: token,78});79} catch (error) {80console.error("Error in /join-room:", error);81res.status(500).send({82error: error.message,83});84}85});8687// Start the Express server88app.listen(port, () => {89console.log(`Express server running on port ${port}`);90});
Test this 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, Postman, HTTPie, or another tool for making this request. To make the request using curl, run the following command in your terminal:
1curl -X POST http://localhost:5000/join-room \2-H "Content-Type: application/json" \3--data '{"roomName": "test room!"}'
The output will be similar to the output below:
1{2"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsImN0..."3}
You can use the site jwt.io 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. The token contains a video grant for the specific room you created. The token will also include fields with other information you provided:
iss: yourTWILIO_API_KEY_SIDsub: yourTWILIO_ACCOUNT_SIDidentity: the randomly generated uuid for the participant's identity
Warning
If the curl request hangs or you receive authentication errors, check that your .env file is located in the root of your project directory (the same directory as server.js). If the .env file is in the wrong location, the server won't be able to load your Twilio credentials, which will cause the request to fail or hang.
You've got 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.