Build a Dynamic Video Chat App with Twilio Video API

In this tutorial, we will create a dynamic video chat application using Twilio Video API, which enables real-time video and audio communication between users. We will build the application using Node.js for the backend and JavaScript for the frontend.


Before we start, make sure you have the following installed and configured:

  • Node.js (v14.x or higher)
  • A Twilio account (sign up for a free trial here)

Setting Up the Project

  1. Create a new directory for the project and navigate to it:
mkdir twilio-video-chat
cd twilio-video-chat
  1. Initialize the project with npm:
npm init -y
  1. Install required dependencies:
npm install express twilio ejs dotenv
  1. Create a .env file to store your Twilio credentials:
touch .env
  1. Add your Twilio Account SID, Auth Token, and API Key SID & Secret to the .env file:

Building the Backend

  1. Create an app.js file in the project root directory:
touch app.js
  1. Add the following code to app.js:
const express = require('express');
const twilio = require('twilio');
const AccessToken = twilio.jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;

const app = express();


app.set('view engine', 'ejs');

app.get('/', (req, res) => {

app.get('/token', (req, res) => {
  const identity = req.query.identity;
  const token = new AccessToken(

  token.identity = identity;
  const grant = new VideoGrant();

    identity: identity,
    token: token.toJwt(),

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Building the Frontend

  1. Create a public directory and an index.ejs file in the views directory:
mkdir public views
touch views/index.ejs
  1. Add the following code to index.ejs:
<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Twilio Video Chat</title>
    /* Add your custom styles here */
  <input type="text" id="identity" placeholder="Enter your name">
  <button id="join">Join Video Chat</button>
  <div id="videos">
    <div id="local"></div>
    <div id="remote"></div>

  <script src="//"></script>
    // Add your JavaScript code here
  1. Add the following JavaScript code inside the <script> tag in index.ejs:
const identityInput = document.getElementById('identity');
const joinButton = document.getElementById('join');
const localVideo = document.getElementById('local');
const remoteVideo = document.getElementById('remote');

joinButton.addEventListener('click', () => {
  const identity = identityInput.value;
  if (!identity) return;

    .then((res) => res.json())
    .then((data) => {
      const { token } = data;
      Twilio.Video.connect(token).then((room) => {
        room.on('participantConnected', (participant) => {

An AI coworker, not just a copilot

View VelocityAI