Build an anonymous chat app in JavaScript

Introduction

We're all familiar with instant messaging and using it to chat to people in realtime. Sometimes, though, we might want an app which allows us to send messages anonymously to friends, or to chat anonymously with strangers in close proximity. An example of such an app is Truth, which lets you talk with people on your contact list without disclosing your identity.

In this tutorial, I'll be showing you how to build a public anonymous chat app in JavaScript (using Node.js and Express on the server, and VanillaJS on the client) and Pusher. Pusher allows us to build scalable and reliable realtime applications, and since we need realtime delivery of chat messages, this is a key component of the chat app. The image below depicts what we will be building:

anonymous-chat-javascript-demo

Getting Started

Let's kick off by signing up for a free Pusher account (or logging in if you already have one). Once you're logged in, create a new Pusher app from the dashboard and make a note of your App ID, Key and Secret, which are unique to an app.

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.

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

Code-up the server

We need a backend which will serve our static files and also accept messages from a client and then broadcast to other connected clients through Pusher. Our backend will be written in Node.js, so we need to set it up.

We need a package.json file, and I'll add it by running the command below. I'll use the defaults provided by hitting enter for every prompt.

$ npm init

With the package.json file added, I'll install Express, body-parser, and Pusher npm packages. Run the following command

$ npm install --save pusher express body-parser

With these packages installed, let's add a new file called server,js with the following content

1var express = require('express');
2var bodyParser = require('body-parser');
3var Pusher = require('pusher');
4
5var app = express();
6app.use(bodyParser.json());
7app.use(bodyParser.urlencoded({ extended: false }));
8
9var pusher = new Pusher({ appId: "APP_ID", key: "APP_KEY", secret:  "APP_SECRET", cluster: "APP_CLUSTER" });
10
11app.post('/message', function(req, res) {
12  var message = req.body.message;
13  pusher.trigger( 'public-chat', 'message-added', { message });
14  res.sendStatus(200);
15});
16
17app.get('/',function(req,res){      
18     res.sendFile('/public/index.html', {root: __dirname });
19});
20
21app.use(express.static(__dirname + '/public'));
22
23var port = process.env.PORT || 5000;
24app.listen(port, function () {
25  console.log(`app listening on port ${port}!`)
26});

With the code above, we have defined an end-point /message which will be used by the client to send in the message it wants to send to another client through Pusher. The other routes are used to serve the static files which we will add later.

Replace the placeholder strings App ID, Secret and Key with the values from your Pusher dashboard.

Add this statement "start": "node server.js" in the script property of our package.json file. This will allow us start the server when we run npm start

Building the frontend

Moving on to the frontend, let's add a new folder called public. This folder will contain our page and JavaScript files. Add a new file called style.css with the content below, which will hold our style definition for the page.

1@import url("http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css");
2.chat
3{
4    list-style: none;
5    margin: 0;
6    padding: 0;
7}
8
9.chat li
10{
11    margin-bottom: 10px;
12    padding-bottom: 5px;
13    border-bottom: 1px dotted #B3A9A9;
14}
15
16.chat li.left .chat-body
17{
18    margin-left: 60px;
19}
20
21.chat li.right .chat-body
22{
23    margin-right: 60px;
24}
25
26
27.chat li .chat-body p
28{
29    margin: 0;
30    color: #777777;
31}
32
33.panel .slidedown .glyphicon, .chat .glyphicon
34{
35    margin-right: 5px;
36}
37
38.body-panel
39{
40    overflow-y: scroll;
41    height: 250px;
42}
43
44::-webkit-scrollbar-track
45{
46    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
47    background-color: #F5F5F5;
48}
49
50::-webkit-scrollbar
51{
52    width: 12px;
53    background-color: #F5F5F5;
54}
55
56::-webkit-scrollbar-thumb
57{
58    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
59    background-color: #555;
60}

Add another file called index.html with the markup below.

1<!DOCTYPE html>
2<html>
3<head>
4    <!-- Latest compiled and minified CSS -->
5    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
6
7    <!-- Optional theme -->
8    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
9
10    <script
11        src="https://code.jquery.com/jquery-2.2.4.min.js"
12        integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
13        crossorigin="anonymous"></script>
14
15    <!-- Latest compiled and minified JavaScript -->
16    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
17
18    <link rel="stylesheet" href="style.css">
19    <script src="https://js.pusher.com/4.0/pusher.min.js"></script>
20    <script src="index.js"></script>
21</head>
22<body>
23    <div class="container">
24    <div class="row form-group">
25        <div class="col-xs-12 col-md-offset-2 col-md-8 col-lg-8 col-lg-offset-2">
26            <div class="panel panel-primary">
27                <div class="panel-heading">
28                    <span class="glyphicon glyphicon-comment"></span> Anonymous Chat
29                    <div class="btn-group pull-right">
30                        <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
31                            <span class="glyphicon glyphicon-chevron-down"></span>
32                        </button>
33                        <ul class="dropdown-menu slidedown">
34                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-refresh">
35                            </span>Refresh</a></li>
36                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-ok-sign">
37                            </span>Available</a></li>
38                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-remove">
39                            </span>Busy</a></li>
40                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-time"></span>
41                                Away</a></li>
42                            <li class="divider"></li>
43                            <li><a href="http://www.jquery2dotnet.com"><span class="glyphicon glyphicon-off"></span>
44                                Sign Out</a></li>
45                        </ul>
46                    </div>
47                </div>
48                <div class="panel-body body-panel">
49                    <ul class="chat">
50
51                    </ul>
52                </div>
53                <div class="panel-footer clearfix">
54                    <textarea id="message" class="form-control" rows="3"></textarea>
55                    <span class="col-lg-6 col-lg-offset-3 col-md-6 col-md-offset-3 col-xs-12" style="margin-top: 10px">
56                        <button class="btn btn-warning btn-lg btn-block" id="btn-chat">Send</button>
57                    </span>
58                </div>
59            </div>
60        </div>
61    </div>
62</div>
63
64<script id="new-message-other" type="text/template">
65    <li class="left clearfix">
66        <span class="chat-img pull-left">
67            <img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle" />
68        </span>
69        <div class="chat-body clearfix">
70            <p>
71                {{body}}
72            </p>
73        </div>
74    </li>
75</script>
76
77<script id="new-message" type="text/template">
78    <li id="{{id}}" class="right clearfix">
79        <div class="chat-body clearfix">
80            <p>
81                {{body}}
82            </p>
83        </div>
84    </li>
85</script>
86
87</body>
88</html>

I'm using a template from bootsnipp which has been slightly modified to display just the name and message.

Add a new file called index.js with the content below. Remember to add the Pusher app details:

1$(document).ready(function(){    
2    var pusher = new Pusher('APP_SECRET', {
3        cluster: 'APP_CLUSTER',
4        encrypted: false
5    });
6
7    let channel = pusher.subscribe('public-chat');
8    channel.bind('message-added', onMessageAdded);
9
10    $('#btn-chat').click(function(){
11        const message = $("#message").val();
12        $("#message").val("");
13
14        $(".chat").append(template);
15
16        //send message
17        $.post( "http://localhost:5000/message", { message } );
18    });
19
20    function onMessageAdded(data) {
21        let template = $("#new-message").html();
22        template = template.replace("{{body}}", data.message);
23
24        $(".chat").append(template);
25    }
26});

With the code in this file, we get the message to send from the page, and then call the server with the message. After that, we connect to Pusher by creating a new Pusher object with the App Secret and the Cluster that you set earlier.

We subscribe to a channel and an event named message-added. The channel is a public channel so it can be named any way you like. I've chosen to prefix mine with public- but that's just my own convention as there are no rules for a public channel. The difference between a public channel (which does not require client to be authenticated), and the other two, are that they're prefixed with private- and presence-.

We bind to the click event of the chat button on the page, then we retrieve the message from the textbox on the page, and then send it to the server with the username. With all we have setup, we can run start the app by running npm start. Here's a glimpse of how it works on my computer.

anonymous-chat-javascript-demo

Wrap Up

This is a app to show how you can use Pusher to send messages in realtime. We built a public anonymous chat app that allows your website visitors to send anonymous messages to each other in realtime.