Author avatar

Peter Mbanugo

Build a Secure Chat Web Application with JavaScript, Auth0 and Pusher

Peter Mbanugo

  • Jan 10, 2019
  • 22 Min read
  • Jan 10, 2019
  • 22 Min read
Front-End JavaScript


Security is hard. When we build applications, we want to allow only registered users to access the application. We want to be able to manage user accounts, see when they last logged in, disable suspicious accounts, and have a dashboard to manage incoming data. We might also need to support multi-factor authentication and social login.

But security isn’t just hard, it also takes a while to implement. What if there’s a service that could handle some part of the development hassle for you? Why spend weeks or months rolling your own auth? This is where Auth0 shines.

This tutorial will give you an in-depth view of how to:

  • build a chat application with Pusher
  • add user authentication with Auth0 Lock
  • manage users from the Auth0 dashboard.

Auth0 and Pusher

Auth0 is an Authentication-as-a-Service (or Identity-as-a-Service) provider focused on encapsulating user authentication and management. The service provides an SDK to allow developers to easily add authentication and manage users. Its user management dashboard assists with breach detection, multi-factor authentication, and passwordless login.

Pusher's APIs and hosted infrastructure allow us to build scalable and reliable realtime applications. At its core, Pusher works through channels and events. Channels provide a way of filtering data and controlling access to different streams of information. Events are the primary method of packaging messages in the Pusher system and form the basis of all communication.

Building the application

We will be building a chat application that will allow users to communicate so that everyone registered to a particular channel can see other users' messages to the channel. It’ll work similarly to how channels work in Slack: just one channel for everybody to communicate.

Here’s what we’ll be building:

Setting up the backend

We’ll start by building the backend which will facilitate receiving and broadcasting chat messages, serving static files, and also setting up Auth0 and Pusher.

First, you’ll need to signup for a Pusher and Auth0 account. Go to and and sign up for an account. To use Pusher API we have to signup and create a Pusher app from the dashboard. We can create as many applications as we want, and each one will get an application ID and secret key which we’ll use to initialize a Pusher instance on client or server side code.

Create a new Pusher account To create a new Pusher app, click the Your apps side menu, then click the Create a new app button below the drawer. This brings up the setup wizard.

  1. Enter a name for the application. In this case I’ll call it “chat”.
  2. Select a cluster.
  3. Select the option “Create app for multiple environments” if you want to have different instances for development, staging and production.
  4. Select Vanilla JS as the frontend and NodeJS as the backend.
  5. Complete the process by clicking Create App button to set up your app instance.

Create new app on Pusher

Since we’re building our backend in Node using Express, let’s initialise a new Node app and install the needed dependencies. Run the following command:

  1. npm init and select the default options
  2. npm i --save body-parser express pusher to install express and the Pusher node package

Add a new file called server.js which will contain logic to authenticate the Pusher client and also render the static files we’ll be adding later. This file will contain the content below:

1var express = require('express');
2var bodyParser = require('body-parser');
3var Pusher = require('pusher');
5var app = express();
7app.use(bodyParser.urlencoded({ extended: false }));
9var pusher = new Pusher({ appId: APP_ID, key: APP_KEY, secret:  APP_SECRET, cluster: eu });
10'/pusher/auth', function(req, res) {
12    var socketId = req.body.socket_id;
13    var channel = req.body.channel_name;
14    var auth = pusher.authenticate(socketId, channel);
15    res.send(auth);
17'/message', function(req, res) {
19    var message = req.body.message;
20    var name =;
21    pusher.trigger( 'private-chat', 'message-added', { message, name });
22    res.sendStatus(200);
26        res.sendFile('/public/index.html', {root: __dirname });
29app.use(express.static(__dirname + '/public'));
31var port = process.env.PORT || 5000;
32app.listen(port, function () {
33    console.log(`app listening on port ${port}!`)

To break down the code, we first instantiate Pusher by passing in an object containing the details of our app ID and secret key. These can be found on the App Keys tab in your Pusher dashboard. Pusher also provides a mechanism for authenticating users to a channel at the point of subscription. To do this, we expose an endpoint on the server that will validate the request and respond with a success or failure. This endpoint will be called by Pusher client libraries and can be named anything. We used the default name for this endpoint on Pusher, which is /pusher/auth. The line var auth = pusher.authenticate(socketId, channel); authenticates the client with Pusher and returns an authentication code to the calling client.

To allow this file to run when we start npm, we update package.json with the following value:

1"scripts": {
2    "start": "node server.js",
3    "test": "echo \"Error: no test specified\" && exit 1"

Create an Auth0 client

To create an Auth0 client

  1. Select Clients from the side menu.
  2. On the new page, click the Create Client button
  3. Enter a name for the app and select Single Page App as an option
  4. Click the Create button to create the client.

An Auth0 client provides us with Client ID and Secret which we’ll use to interact with Auth0 from the code. On the settings tab, we can see the Name, Client Id, Secret, Client Type and many more. I want to enable Cross-Origin Resource Sharing (CORS) for my domain http://localhost:5000 and set the log out URL and the post-authentication redirect URL. Update the following settings with http://localhost:5000:

  1. Allowed Callback URLs
  2. Allowed Logout URLs
  3. Allowed Origins (CORS)

Building the frontend

With the backend all good to go, we build the web page that will facilitate messaging. Create a folder named public which will contain the html and javascript file. Create two new files style.css and index.html with the following content:


1@import url("");
4    list-style: none;
5    margin: 0;
6    padding: 0;
7} li
10    margin-bottom: 10px;
11    padding-bottom: 5px;
12    border-bottom: 1px dotted #B3A9A9;
13} li.left .chat-body
16    margin-left: 60px;
17} li.right .chat-body
20    margin-right: 60px;
22 li .chat-body p
25    margin: 0;
26    color: #777777;
28.panel .slidedown .glyphicon, .chat .glyphicon
30    margin-right: 5px;
34    overflow-y: scroll;
35    height: 250px;
39    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
40    background-color: #F5F5F5;
44    width: 12px;
45    background-color: #F5F5F5;
49    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
50    background-color: #555;


1<!-- template from -->
2<!DOCTYPE html>
5    <!-- Latest compiled and minified CSS -->
6    <link rel="stylesheet" href="" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
7    <!-- Optional theme -->
8    <link rel="stylesheet" href="" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
9    <script
10        src=""
11        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
12        crossorigin="anonymous"></script>
13    <!-- Latest compiled and minified JavaScript -->
14    <script src="" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
15    <link rel="stylesheet" href="style.css">
16    <script src=""></script>
17    <script src=""></script>
18    <script src="index.js"></script>
21    <div class="container">
22    <div class="row form-group">
23        <div class="col-xs-12 col-md-offset-2 col-md-8 col-lg-8 col-lg-offset-2">
24            <div class="panel panel-primary">
25                <div class="panel-heading">
26                    <span class="glyphicon glyphicon-comment"></span> <span id="username"></span>
27                    <div class="btn-group pull-right">
28                        <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
29                            <span class="glyphicon glyphicon-chevron-down"></span>
30                        </button>
31                        <ul class="dropdown-menu slidedown">
32                            <li><a><span class="glyphicon glyphicon-refresh">
33                            </span>Refresh</a></li>
34                            <li><a><span class="glyphicon glyphicon-ok-sign">
35                            </span>Available</a></li>
36                            <li><a><span class="glyphicon glyphicon-remove">
37                            </span>Busy</a></li>
38                            <li><a><span class="glyphicon glyphicon-time"></span>
39                                Away</a></li>
40                            <li class="divider"></li>
41                            <li><a id="logout"><span class="glyphicon glyphicon-off"></span>
42                                Sign Out</a></li>
43                        </ul>
44                    </div>
45                </div>
46                <div class="panel-body body-panel">
47                    <ul class="chat">
49                    </ul>
50                </div>
51                <div class="panel-footer clearfix">
52                    <textarea id="message" class="form-control" rows="3"></textarea>
53                    <span class="col-lg-6 col-lg-offset-3 col-md-6 col-md-offset-3 col-xs-12" style="margin-top: 10px">
54                        <button class="btn btn-warning btn-lg btn-block" id="btn-chat">Send</button>
55                    </span>
56                </div>
57            </div>
58        </div>
59    </div>
61<script id="new-message" type="text/template">
62    <li id="{{id}}" class="right clearfix">
63        <div class="chat-body clearfix">
64            <div class="header">
65                <small class="text-muted">{{name}}</small>
66            </div>
67            <p>
68                {{body}}
69            </p>
70        </div>
71    </li>

This file uses template from bootsnip and also includes a script reference to Auth0 Lock <script src=""></script>. Lock is a drop-in authentication widget that provides a standard set of behaviours required for login and a customizable user interface. It provides a simple way to integrate with Auth0 with very minimal configuration.

We want to allow users to sign in when they enter the application, get authenticated, and only then be able to send messages. Add a new file index.js with the following content:

2    // Initiating our Auth0Lock
3    let lock = new Auth0Lock(
4        'CLIENT_ID',
5        'CLIENT_DOMAIN',//example:
6        {
7            auth: {
8                params: {
9                    scope: 'openid profile'
10                }
11            },
12            autoclose: true,
13            closable: false,
14            rememberLastLogin: true
15        }
16    );
18    let profile = JSON.parse(localStorage.getItem('profile'));
19    let isAuthenticated = localStorage.getItem('isAuthenticated');
21    function updateValues(userProfile, authStatus) {
22        profile = userProfile;
23        isAuthenticated = authStatus;
24    }
26    if(!isAuthenticated && !window.location.hash){
27;//show Lock widget
28    }
30    // Listening for the authenticated event
31    lock.on("authenticated", function(authResult) {
32        // Use the token in authResult to getUserInfo() and save it to localStorage
33        lock.getUserInfo(authResult.accessToken, function(error, profile) {
34            if (error) {
35                // Handle error
36                return;
37            }
39            localStorage.setItem('accessToken', authResult.accessToken);
40            localStorage.setItem('profile', JSON.stringify(profile));
41            localStorage.setItem('isAuthenticated', true);
42            updateValues(profile, true);
43            $("#username").html(;
44        });
45    });

We initialise Lock by passing it the Client Id of the app, your user domain which starts with your username followed by or .{YOUR_SELECTED_REGION} e.g The widget is configurable, so we can send in configuration options like closable, autoClose, and auth. Within the auth option, we tell it to return the openid and profile claims.

We check if the user is authenticated and show the widget when they’re not. Once the user is authenticated, Lock emits the authenticated event to which we’ve subscribed. When the event is raised, we store the user profile and other credentials to localStorage and set the user’s name to be displayed on the page. Once the user is authenticated, we want to connect to Pusher and send messages across. Update index.js with the following code:

1if(!isAuthenticated && !window.location.hash){
6    // Enable pusher logging - don't include this in production
7    Pusher.logToConsole = true;
9    var pusher = new Pusher('APP_SECRET', {
10        cluster: 'e.g eu',
11        encrypted: false
12    });
14    var channel = pusher.subscribe('private-chat');
15    channel.bind('message-added', onMessageAdded);
18function onMessageAdded(data) {
19    let template = $("#new-message").html();
20    template = template.replace("{{body}}", data.message);
21    template = template.replace("{{name}}",;
23    $(".chat").append(template);

Pusher is initialised with the APP_SECRET and CLUSTER which you can get from the app dashboard on Pusher. We subscribe to a channel called private-chat. Pusher has 3 types of channels: Public, Private and Presence channel. Private and Presence channels let your server control access to the data you are broadcasting. Presence channels go further to force subscribers to register user information when subscribing. Private channels are named starting with private- and authenticated in the server when subscribing.

And finally we want to send the message to the user when they click send and also log them out when they select signout. Update index.js with the code below

2    const message = $("#message").val();
3    $("#message").val("");
4        //send message
5    $.post( "http://localhost:5000/message", { message, name: } );
8$("#logout").click((e) => {
9    e.preventDefault();
10    logout();
13function logout(){
14    localStorage.clear();
15    isAuthenticated = false;
16    lock.logout({
17        returnTo: "http://localhost:5000"
18    });

When the user clicks the send button, we take the message and put it in an object with the user’s profile name and send it to the /message endpoint on the server. When the logout button is clicked, it calls the logout function which clears the data stored in localStorage and call lock.logout() which logs the user out on Auth0 and redirects them back to our website. With all these additions, index.js should have the following content:

2    // Initiating our Auth0Lock
3    let lock = new Auth0Lock(
4        'CLIENT_ID',
5        'CLIENT_DOMAIN',
6        {
7            auth: {
8                params: {
9                    scope: 'openid profile'
10                }
11            },
12            autoclose: true,
13            closable: false,
14            rememberLastLogin: true
15        }
16    );
18    // Listening for the authenticated event
19    lock.on("authenticated", function(authResult) {
20        // Use the token in authResult to getUserInfo() and save it to localStorage
21        lock.getUserInfo(authResult.accessToken, function(error, profile) {
22            if (error) {
23                // Handle error
24                console.log(error);
25                return;
26            }
28            localStorage.setItem('accessToken', authResult.accessToken);
29            localStorage.setItem('profile', JSON.stringify(profile));
30            localStorage.setItem('isAuthenticated', true);
31            updateAuthenticationValues(profile, true);
32            $("#username").html(;
33        });
34    });
36    let profile = JSON.parse(localStorage.getItem('profile'));
37    let isAuthenticated = localStorage.getItem('isAuthenticated');
39    function updateAuthenticationValues(userProfile, authStatus) {
40        profile = userProfile;
41        isAuthenticated = authStatus;
42    }
44    $("#logout").click((e) => {
45        e.preventDefault();
46        logout();
47    });
49    function logout(){
50        localStorage.clear();
51        isAuthenticated = false;
52        lock.logout({
53            returnTo: "http://localhost:5000"
54        });
55    }
57    function onMessageAdded(data) {
58        let template = $("#new-message").html();
59        template = template.replace("{{body}}", data.message);
60        template = template.replace("{{name}}",;
62        $(".chat").append(template);
63    }
65    if(!isAuthenticated && !window.location.hash){
67    }
68    else{
69        if(profile){
70            $("#username").html(;
71        }
73        // Enable pusher logging - don't include this in production
74        Pusher.logToConsole = true;
76        var pusher = new Pusher('APP_SECRET', {
77            cluster: 'eu',
78            encrypted: false
79        });
81        var channel = pusher.subscribe('private-chat');
82        channel.bind('message-added', onMessageAdded);
84        $('#btn-chat').click(function(){
85            const message = $("#message").val();
86            $("#message").val("");
87                //send message
88            $.post( "http://localhost:5000/message", { message, name: } );
89        });  
90    }

To test the app, run npm start on the terminal and open http://localhost:5000 on two separate browsers. Here’s a run through of it:


This is an app to show how you can use Pusher to send messages in real-time and secure the channels, add user authentication and account management with Auth0, and easily integrate to Auth0 using Auth0 Lock. On your Auth0 dashboard you can see the total number of users, logins and new signups.

You can also see all your users when you click on the Users side menu. On this page you can see the list of your users and their mode of login.

Selecting a user takes you to a more detailed page where you can take various actions on the account, for example, blocking an account or sending a verification email.

Pusher also allows you to view statistics regarding your application. To do this, go to your application dashboard, under Stats, where you’ll see statistics concerning your application, such as connection frequency and how many messages were sent through that app. The combination of these two technologies makes it faster and easier to build real-time secured applications.

You can find the code here on GitHub. Hopefully this guide has been an effective introduction to Auth0 and Pusher and a quality springboard to help you set up authentication faster in your upcoming applications.

Thanks for reading this guide. Till next time.

This was originally published on Pusher.