🎉 New release for Pusher Chatkit - Webhooks! Extend your in-app chat functionality
Hide
Products
chatkit_full-logo

Extensible API for in-app chat

channels_full-logo

Build scalable realtime features

beams_full-logo

Programmatic push notifications

Developers

Docs

Read the docs to learn how to use our products

Tutorials

Explore our tutorials to build apps with Pusher products

Support

Reach out to our support team for help and advice

Sign in
Sign up

Building a chat app with emoji reactions - Part 1: Building the backend

  • Neo Ighodaro
May 3rd, 2019
For this part of the series, you will need Node.js set up on your machine.

Introduction

This is the first of a three-part series on how to build a simple chat application to show the use of emoji reactions. We will show how you add emoji reactions to messages in a chat room, something we see in Slack, Discord and the likes of them. In this part, we will focus on setting up the Channels and Chatkit apps as well as build our backend server.

Prerequisites

To follow along, it is expected that you have the following requirements:

  • Pusher Chatkit account. Create one here.
  • Pusher Channels account. Create one here.
  • Node.js and NPM installed on your machine.
  • Knowledge of JavaScript and Node.js.

Creating our Pusher Channels app

The first thing you will do here is to create a new Pusher Channels app. Open your dashboard and select the Create new app button.

Enter your app name - chatkit-emoji and select the Create my app button. When your app is created, you will have access to the keys through the App Keys tab. Keep these keys readily available as you will need them later in this post and the series.

Creating our Chatkit app

Next, go to your Chatkit dashboard and create a new instance. Name the instance chatkit-emoji.

The keys and secrets for your Chatkit app are available on the Credentials tab. Keep the keys available as you will need them soon.

To reduce the complexity of the mobile apps we will create in the next two parts, we will create two new users, a room and then we will add messages to the room.

Open the Console tab of the chatkit-emoji instance and create a new user

The name of the user we created is neo. After that, create another user. The name of our second user is joe. Next, choose any of your users, and then select the Create and join a room option available to them like this:

Create a new room called general. After that, select the next user and make that user join the general room too. After that, create about two messages and add to the general room.

Building the Node.js server

To get started building the server, create a new folder chatkit-emoji-backend in any directory of your choice. You can easily do that by running this command:

    $ mkdir chatkit-emoji-backend

Next, move into the folder:

    $ cd chatkit-emoji-backend

The first file we will create is the package.json file. Inside the file, paste this snippet:

    // File: ./package.json
    {
      "name": "chatkit-emoji-backend",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "@pusher/chatkit-server": "^1.1.0",
        "body-parser": "^1.18.3",
        "express": "^4.16.4",
        "pusher": "^2.2.0"
      }
    }

This file contains the key details of the project and the dependencies to be used in it. Next, create an index.js file. Open the file and paste paste this snippet:

    // File: ./index.js
    const express = require("express");
    const bodyParser = require("body-parser");
    const Pusher = require("pusher");
    const Chatkit = require("@pusher/chatkit-server");
    const app = express();

    const pusher = new Pusher({
      appId: "PUSHER_APP_ID",
      key: "PUSHER_KEY",
      secret: "PUSHER_SECRET",
      cluster: "PUSHER_CLUSTER",
      encrypted: true
    });

    const chatkit = new Chatkit.default({
      instanceLocator: "CHATKIT_INSTANCE_LOCATOR",
      key: "CHATKIT_KEY"
    });

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    // TODO: WE WILL ADD ROUTES HERE!

    const server = app.listen(3000, () => {
      console.log(`Express server running on port ${server.address().port}`);
    });

From the above snippet, we first required our dependencies and assigned them to variables. Next, we went ahead to initialize the Pusher and Chatkit objects with their keys. After that, we added the body parser to the middleware to help us parse our request body, and finally, we serve the app to port 3000.

Replace the PUSHER_* and CHATKIT_* placeholders with their respective values from the dashboard.

Our app is not yet complete as we have no route defined yet. Lets us now define routes that our client applications will use. Add this snippet in the index.js file:

    // File: ./index.js

    // [...]

    app.post("/users", (req, res) => {
      const userId = req.body.userId;

      chatkit
        .createUser({
          id: userId,
          name: userId
        })
        .then(() => {
          res.sendStatus(200);
        })
        .catch(err => {
          if (err.error === "services/chatkit/user_already_exists") {
            console.log(`User already exists: ${userId}`);
            res.sendStatus(200);
          } else {
            res.status(err.status).json(err);
          }
        });
    });

    app.post("/token", (req, res) => {
      const result = chatkit.authenticate({
        userId: req.query.user_id
      });

      res.status(result.status).send(result.body);
    });

    app.post("/updateEmoji", (req, res) => {
      pusher.trigger(req.body.roomId, "emoji-event", {
        emoji: req.body.emoji,
        count: req.body.count,    
        userIds: req.body.userIds,
        messageId: req.body.messageId
      });

      res.send(200);
    });

    // [...]

From the above snippet, we have three routes:

  • /users - This is the endpoint that creates a new user for us on Chatkit. After the user is created, a status 200 is sent to show it was successful. We also check for cases where a user exists and we return a success too. While testing, we won't create any new user so this endpoint is here to authenticate existing users.
  • /token - This endpoint will not be directly used by us but by the respective client SDKs (for iOS and Android). This endpoint generates an access token for the user.
  • /updateEmoji - This endpoint is what we will use to send emoji reactions for the messages within a room through Channels.

Next, install the dependencies for your app. Run this command in your chatkit-emoji-backend folder:

    $ npm install

After that, run the server using this command:

    $ node index.js

This should display Express server running on port 3000 in your terminal.

Conclusion

We have successfully completed the first part of the series. In this part, we were able to create our Pusher Chatkit app, create our Pusher Channels app and finally build the backend of our system with Node.js.

In subsequent parts, we will build client apps (iOS and Android) to utilize what we have in this part. Feel free to interact with the GitHub repo and play around with it

Clone the project repository
  • Android
  • Chat
  • JavaScript
  • iOS
  • Node.js
  • Kotlin
  • Swift
  • Chatkit
  • Channels

Products

  • Channels
  • Chatkit
  • Beams

© 2019 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.