Twilio Client Javascript Quickstart

Ready to add voice communication to your web application with Twilio's JavaScript Browser client? You'll need to set up two Twilio Functions and do some front-end work, but this quickstart will... quickly... show you the ropes.

Let's get cracking!

Gather Twilio account information

The first thing we need to do is grab all the necessary information from our Twilio account. To set up our back-end for Twilio Client, we will need two values from our account:

Config Value Description
TwiML App SID The TwiML application with a voice URL configured to access your server running this app - create one in the console here. Also, you will need to configure the Voice "REQUEST URL" on the TwiML app to point to a Twilio function you will create.
Twilio Phone # A Twilio phone number in E.164 format - you can get one here

Download the front end

You'll need a front end for this Twilio Client for Javascript quickstart - the HTML, CSS, and, of course, Javascript. You're welcome to use any kind of front end web technology you want for your own application, but we've got a pretty simple little set of code for you to use to get started. Go ahead and download a zipped up copy of the Twilio Client for JS source code, or check out the Twilio Client for JS GitHub repo

We'll use this code a little bit later, after we get the Twilio Functions set up. You'll need to change the location of a URL in public/quickstart.js to point to your function.

Working with Twilio Functions

Most of the work you'll be doing with Twilio Client for Javascript is front-end web development - but there are a few things you'll need to set up on the server side.  We've got a really simple way for you to get started - Twilio Functions!

Functions is Twilio's serverless code execution environment that lets you write Node.js code that can respond to Twilio webhooks or to regular HTTP POST or GET requests. 

You can also always write your own server code using any of Twilio's supported server side languages (Node.js, Python, Ruby, C#, Java, or PHP) - check out how to create capability tokens.

Creating the quickstart functions

To get you up and running with this quickstart, you can use a template to create your functions. Start by going to the Functions page in the Twilio Console. You can add new functions with the plus button on that screen.

Go ahead and click that plus button, and then look for the Twilio Client Quickstart template - it's outlined in the image below:

Twilio Client Quickstart Functions Template

Click that Twilio Client Quickstart template button, and then you can configure your functions - while most of these templates only create one function, the template we use for this quickstart creates two functions - one to provide capability tokens to your Twilio Client, and one to provide TwiML via a webhook. 

Configuring your functions

After selecting the Twilio Client Quickstart template, you'll be asked to configure your function with two values - the TWIML_APP_SID and the CALLER_ID. 

Twilio Client QS Configuration

If you didn't set those up earlier in this quickstart, go back and do it now - you'll need both of these values to continue with the setup process.

Click Create, and you'll get two new functions. Your Functions page will look like this:

Twilio Client QS Function Listing

Point your TwiML app to your function

We need to tell Twilio what to do with incoming voice requests for that TwiML app. Twilio will fire off a webhook to your function, but we need to supply that URL in the Twilio console before it will work.

All of your functions will share a common subdomain name that is unique to your account, but the paths will be different. The path for the Voice Calls function will be /client-voice. If you want to copy the entire URL for that function, select it in the console, and there will be a copy button next to the URL:

Twilio Client QS Copy Voice URL

 

Now, configure the Voice "REQUEST URL" on your TwiML App to use the Voice Calls function.

Twilio Client QS TwiML App

Under Voice, set the Request URL to your function's URL, and then click Save.  

Setting up your capability token

The last configuration step is to set the URL of your capability token in the front end web application. The subdomain that Twilio uses is unique to your account, so go ahead and find this line in quickstart.js: 

$.getJSON('https://YOUR_FUNCTION_SUBDOMAIN_HERE.twil.io/capability-token')

Replace the placeholder (YOUR_FUNCTION_SUBDOMAIN_HERE) with your Twilio Function subdomain, and then save the file. Of course, if you want to see what is going on behind the scenes, take a quick peek at the source while you're there!

All set! Let's go ahead and spin this quickstart up.

Run a local HTTP server

Our back end logic for the application is all running on Twilio Functions, but to use Twilio Client, you will need to run the front end from a web server on your computer. Just opening the HTML page up in your browser (as a file:// URL) won't work in Google's Chrome web browser, for instance.

Luckily, you don't need to set up a complicated development environment - you just need to serve static files off of your computer. We recommend the http-server Node.js module. If you don't have Node.js installed on your computer, download Node for your operating system first, and follow the directions to set it up - it's pretty easy!

Once you have Node all ready to go, you can install http-server using this command:

npm install http-server -g

If you are on macOS or Linux, you will probably need to run that command as the superuser (or admin account)

sudo npm install http-server -g

Now, just run the HTTP server in the directory that has the quickstart sample application:

http-server

Your web site will be running at http://localhost:8080/ - go ahead and try it out! Be sure to use Chrome, Firefox, or a recent version of Safari.

Explore the starter app

Time to have some fun! When you visit the homepage of the starter application, you should see a page which looks like this:

TwilioClientQuickstart.png

You have been assigned a random client name and are ready to make phone calls. Type in a phone number to make a call, or type in the client name of another user. Try opening the app in another browser window and calling yourself. (Have fun with the audio feedback!)

The HTML and CSS in the starter application aren't very complex, but the JavaScript driving this application has some very important jobs: 

  1. Fetch a Capability Token from your Twilio Function via Ajax
  2. Initialize the Twilio Client JavaScript library
  3. Handle UI events to to make phone calls
  4. Handle Twilio Client events to display status messages

Creating capability tokens

Now that you have the front end up and running, you can add capability token generation to your project. You will probably want to be able to create these tokens, and then add one or more scopes to the token. These scopes give your users the ability to make outgoing or receive incoming voice calls using the Twilio Client Javascript library. Learn more about Capability Tokens, or explore a more in-depth tutorial about Capability Tokens for Twilio Client.

Twilio supports six languages for creating capability tokens (Java, C#, Node.js, Ruby, Python, and PHP). The following code listing has examples for each of these languages.

Loading Code Samples...
Language
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
const http = require('http');
const express = require('express');
const twilio = require('twilio');

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new twilio.Capability(accountSid, authToken);
  capability.allowClientOutgoing(appSid);
  capability.allowClientIncoming('joey');
  const token = capability.generate();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/');
const http = require('http');
const express = require('express');
const ClientCapability = require('twilio').jwt.ClientCapability;

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new ClientCapability({
    accountSid: accountSid,
    authToken: authToken,
  });
  capability.addScope(
    new ClientCapability.OutgoingClientScope({ applicationSid: appSid })
  );
  capability.addScope(new ClientCapability.IncomingClientScope('joey'));
  const token = capability.toJwt();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/token/');
// In Package Manager, run:
// Install-Package Twilio.Client -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio;

public class TokenController : Controller
{
  // GET: Token
  public ActionResult Index()
  {
    // put your Twilio API credentials here
    string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string authToken = "your_auth_token";

    // put your Twilio Application Sid here
    string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    var capability = new TwilioCapability(accountSid, authToken);
    capability.AllowClientOutgoing(appSid);
    capability.AllowClientIncoming("joey");
    string token = capability.GenerateToken();

    return Content(token, "application/jwt");
  }
}
<?php
include 'Services/Twilio/Capability.php';

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming('joey');
$token = $capability->generateToken();

echo $token;
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::Util::Capability.new account_sid, auth_token
  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  capability.allow_client_incoming 'joey'
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
// In Package Manager, run:
// Install-Package Twilio -Pre
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.Jwt;
using Twilio.Jwt.Client;

public class TokenController : Controller
{
    // GET: Token
    public ActionResult Index()
    {
        // Put your Twilio API credentials here
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        // Put your Twilio Application SID here
        const string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        var scopes = new HashSet<IScope>
        {
            new OutgoingClientScope(appSid),
            new IncomingClientScope("joey")
        };
        var capability = new ClientCapability(accountSid, authToken, scopes: scopes);

        return Content(capability.ToJwt(), "application/jwt");
    }
}
<?php
include "vendor/autoload.php";

use Twilio\Jwt\ClientToken;

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming('joey');
$token = $capability->generateToken();

echo $token;
from flask import Flask, Response
from twilio.util import TwilioCapability

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = TwilioCapability(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    capability.allow_client_incoming('joey')
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::JWT::Capability.new(account_sid, auth_token)

  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing('APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
  capability.allow_client_incoming('joey')
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.sdk.client.TwilioCapability;

public class TwilioServlet extends HttpServlet {

    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // Find an application Sid from twilio.com/user/account/apps
        String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN);
        capability.allowClientOutgoing(applicationSid);
        capability.allowClientIncoming("joey");

        String token = capability.generateToken();

        response.setContentType("application/jwt");
        response.getWriter().print(token);
    }
}
from flask import Flask, Response
from twilio.jwt.client import ClientCapabilityToken

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = ClientCapabilityToken(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    capability.allow_client_incoming('joey')
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.twilio.jwt.client.ClientCapability;
import com.twilio.jwt.client.IncomingClientScope;
import com.twilio.jwt.client.OutgoingClientScope;
import com.twilio.jwt.client.Scope;

public class TwilioServlet extends HttpServlet {

  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Find an application Sid from twilio.com/user/account/apps
    String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    OutgoingClientScope outgoingScope = new OutgoingClientScope.Builder(applicationSid).build();
    IncomingClientScope incomingScope = new IncomingClientScope("joey");

    List<Scope> scopes = Lists.newArrayList(outgoingScope, incomingScope);

    ClientCapability capability = new ClientCapability.Builder(ACCOUNT_SID, AUTH_TOKEN)
        .scopes(scopes)
        .build();

    String token = capability.toJwt();

    response.setContentType("application/jwt");
    response.getWriter().print(token);
  }
}
Generate Twilio Client Capability Token

For complete, runnable applications for each of these languages, download source code from these GitHub repositories:

Get Help

Need some extra help with the Client? Tweet at us or contact support and we'll get you running quickly. Have some fun with Twilio Client in the browser, and make sure to let us know what you're building!

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

Loading Code Samples...
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 6.x
  • 7.x
SDK Version:
  • 2.x
  • 3.x
SDK Version:
  • 4.x
  • 5.x
SDK Version:
  • 5.x
  • 6.x
SDK Version:
  • 4.x
  • 5.x
const http = require('http');
const express = require('express');
const twilio = require('twilio');

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new twilio.Capability(accountSid, authToken);
  capability.allowClientOutgoing(appSid);
  capability.allowClientIncoming('joey');
  const token = capability.generate();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/');
const http = require('http');
const express = require('express');
const ClientCapability = require('twilio').jwt.ClientCapability;

const app = express();

app.get('/token', (req, res) => {
  // put your Twilio API credentials here
  const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
  const authToken = 'your_auth_token';

  // put your Twilio Application Sid here
  const appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

  const capability = new ClientCapability({
    accountSid: accountSid,
    authToken: authToken,
  });
  capability.addScope(
    new ClientCapability.OutgoingClientScope({ applicationSid: appSid })
  );
  capability.addScope(new ClientCapability.IncomingClientScope('joey'));
  const token = capability.toJwt();

  res.set('Content-Type', 'application/jwt');
  res.send(token);
});

app.post('/voice', (req, res) => {
  // TODO: Create TwiML response
});

http.createServer(app).listen(1337, '127.0.0.1');
console.log('Twilio Client app server running at http://127.0.0.1:1337/token/');
// In Package Manager, run:
// Install-Package Twilio.Client -DependencyVersion HighestMinor

using System.Web.Mvc;
using Twilio;

public class TokenController : Controller
{
  // GET: Token
  public ActionResult Index()
  {
    // put your Twilio API credentials here
    string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    string authToken = "your_auth_token";

    // put your Twilio Application Sid here
    string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    var capability = new TwilioCapability(accountSid, authToken);
    capability.AllowClientOutgoing(appSid);
    capability.AllowClientIncoming("joey");
    string token = capability.GenerateToken();

    return Content(token, "application/jwt");
  }
}
<?php
include 'Services/Twilio/Capability.php';

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new Services_Twilio_Capability($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming('joey');
$token = $capability->generateToken();

echo $token;
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::Util::Capability.new account_sid, auth_token
  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  capability.allow_client_incoming 'joey'
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
// In Package Manager, run:
// Install-Package Twilio -Pre
using System.Collections.Generic;
using System.Web.Mvc;
using Twilio.Jwt;
using Twilio.Jwt.Client;

public class TokenController : Controller
{
    // GET: Token
    public ActionResult Index()
    {
        // Put your Twilio API credentials here
        const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        const string authToken = "your_auth_token";

        // Put your Twilio Application SID here
        const string appSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

        var scopes = new HashSet<IScope>
        {
            new OutgoingClientScope(appSid),
            new IncomingClientScope("joey")
        };
        var capability = new ClientCapability(accountSid, authToken, scopes: scopes);

        return Content(capability.ToJwt(), "application/jwt");
    }
}
<?php
include "vendor/autoload.php";

use Twilio\Jwt\ClientToken;

// put your Twilio API credentials here
$accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
$authToken  = 'your_auth_token';
$appSid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$capability->allowClientIncoming('joey');
$token = $capability->generateToken();

echo $token;
from flask import Flask, Response
from twilio.util import TwilioCapability

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = TwilioCapability(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    capability.allow_client_incoming('joey')
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
require 'twilio-ruby'
require 'sinatra'

get '/token' do
  account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
  auth_token = 'your_auth_token'
  capability = Twilio::JWT::Capability.new(account_sid, auth_token)

  # Create an application sid at
  # twilio.com/console/phone-numbers/dev-tools/twiml-apps and use it here
  capability.allow_client_outgoing('APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
  capability.allow_client_incoming('joey')
  token = capability.generate

  content_type 'application/jwt'
  token
end

# TODO: post '/voice' do
package com.twilio;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import com.twilio.sdk.client.TwilioCapability;

public class TwilioServlet extends HttpServlet {

    public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public static final String AUTH_TOKEN = "your_auth_token";

    public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // Find an application Sid from twilio.com/user/account/apps
        String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
        TwilioCapability capability = new TwilioCapability(ACCOUNT_SID, AUTH_TOKEN);
        capability.allowClientOutgoing(applicationSid);
        capability.allowClientIncoming("joey");

        String token = capability.generateToken();

        response.setContentType("application/jwt");
        response.getWriter().print(token);
    }
}
from flask import Flask, Response
from twilio.jwt.client import ClientCapabilityToken

app = Flask(__name__)


@app.route('/token', methods=['GET'])
def get_capability_token():
    """Respond to incoming requests."""

    # Find these values at twilio.com/console
    account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    auth_token = 'your_auth_token'

    capability = ClientCapabilityToken(account_sid, auth_token)

    # Twilio Application Sid
    application_sid = 'APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    capability.allow_client_outgoing(application_sid)
    capability.allow_client_incoming('joey')
    token = capability.generate()

    return Response(token, mimetype='application/jwt')


if __name__ == "__main__":
    app.run(debug=True)
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.common.collect.Lists;
import com.twilio.jwt.client.ClientCapability;
import com.twilio.jwt.client.IncomingClientScope;
import com.twilio.jwt.client.OutgoingClientScope;
import com.twilio.jwt.client.Scope;

public class TwilioServlet extends HttpServlet {

  public static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
  public static final String AUTH_TOKEN = "your_auth_token";

  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Find an application Sid from twilio.com/user/account/apps
    String applicationSid = "APXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

    OutgoingClientScope outgoingScope = new OutgoingClientScope.Builder(applicationSid).build();
    IncomingClientScope incomingScope = new IncomingClientScope("joey");

    List<Scope> scopes = Lists.newArrayList(outgoingScope, incomingScope);

    ClientCapability capability = new ClientCapability.Builder(ACCOUNT_SID, AUTH_TOKEN)
        .scopes(scopes)
        .build();

    String token = capability.toJwt();

    response.setContentType("application/jwt");
    response.getWriter().print(token);
  }
}