Chatkit JavaScript Quick Start

This quick start will take you through the basics of using Chatkit with JavaScript.

Our aim is to help you build your first (minimal) Chatkit application. It should take about 15 minutes to follow along (or a few minutes to read, if you’d prefer).

If you're looking for the complete code, scroll to the bottom.

What Is Chatkit?

Great question 😏 !

Chatkit is a hosted API that helps you build impressive chat features into your applications with less code. It offers you features like:

  • Group chat
  • One-to-one chat
  • Private chat
  • Typing indicators
  • "Who's online" presence
  • Read receipts
  • Photo, video, and audio messages

Using our cross-platform SDKs, all chat data is sent through our hosted API where we manage chat state and broadcast it to your clients:

We manage your chat data for you, making it easy to show historical messages, typing indicators, etc. with little to no custom server code. You'll never have to worry about scale, reliability, or infrastructure, we take care of it all for you.

Getting Started

To get started with Chatkit, you’ll first need to create a Chatkit instance.

You can have as many instances as you want. To create your first, head to the dashboard, hit Create new +, then give your instance a name. I will call mine “Getting Started App”:

Keys

Once you’ve created your Chatkit instance, head to the Keys tab and take note of your Instance Locator:

You’ll need this later to connect to Chatkit.

Create a User

Before someone can connect to a Chatkit instance, you must first create a Chatkit user.

Normally, you would do this programmatically on your server, using one of our server SDKs:

1
2
3
4
5
6
7
8
9
10
11
// Example Node code. Do not copy

const chatkit = new Chatkit.default({
  instanceLocator: "YOUR INSTANCE LOCATOR",
  key: "YOUR SECRET KEY"
})

chatkit.createUser({
  id: "bookercodes",
  name: "Alex Booker"
})

That being said, you can also create users manually from the Inspector tab.

I will call mine “bookercodes”:

Create a Room

With Chatkit, all messages are sent to a room. You can have as many rooms as you want.

For example, if you want to build a one-to-one chat, we encourage you to create a room with just two users.

Rooms can be created programmatically or from the Inspector tab. I will use the Inspector tab and call mine “General”:

Remember, while the Inspector is a handy tool to get started and occasionally debug your app, we didn’t design it for production use.

Going forward, we encourage you to create users and rooms programmatically.

Enable the Test Token Provider

Chatkit has been designed to integrate seamlessly with your existing authentication system.

That being said, to help you get started quickly, we provide a test token provider which you can enable in the Settings tab:

Once enabled, take note of your test token provider endpoint. You’ll need it in the next step.

Please remember, the test token provider is insecure and unsuitable for production. To learn more about production-grade authentication, see our authentication documentation.

Setting Up and Installing Chatkit

If you’re following along, create a index.html file and reference @pusher/chatkit:

1
2
3
4
5
6
7
8
9
10
11
<html lang=en>
  <head>
    <meta charset=utf-8>
    <title>Chatkit demo</title>
  </head>
  <body>
    <script src="https://unpkg.com/@pusher/chatkit@0.7.5/dist/web/chatkit.js"></script>
    <script></script>
  </body>
</html>

Initialise Chatkit

Once installed, you’ll have access to Chatkit.ChatManager and Chatkit.TokenProvider.

In the empty <script> tag, initialise them both:

1
2
3
4
5
6
7
8
9
const tokenProvider = new Chatkit.TokenProvider({
  url: "YOUR TEST TOKEN ENDPOINT"
});

const chatManager = new Chatkit.ChatManager({
  instanceLocator: "YOUR INSTANCE LOCATOR",
  userId: "YOUR USER ID",
  tokenProvider: tokenProvider
});

Remember to replace "YOUR TEST TOKEN ENDPOINT", "YOUR INSTANCE LOCATOR", and "YOUR USER ID" with your own values.

Connect to Chatkit

Beneath chatManager, connect to Chatkit:

1
2
3
4
5
6
7
8
9
10
const tokenProvider = new Chatkit.TokenProvider({
  url: "YOUR TEST TOKEN ENDPOINT"
});
 
const chatManager = new Chatkit.ChatManager({
  instanceLocator: "YOUR INSTANCE LOCATOR",
  userId: "YOUR USER ID",
  tokenProvider: tokenProvider
});
 
11
12
13
14
15
16
17
18
chatManager
  .connect()
  .then(currentUser => {
    console.log("Connected as user ", currentUser);
  })
  .catch(error => {
    console.error("error:", error);
  });

When using Chatkit, all functions are asynchronous and return a Promise. connect is no exception.

Subscribe to a Room

When the call to connect has finished, you’ll receive the currentUser. Almost all interactions with Chatkit happen on currentUser.

When we created our room via the dashboard inspector earlier on our created user was automatically added as a member of the room because they created the room. As a result, the currentUser's rooms property will be populated with the room we created so we can subscribe to it straight away.

1
2
3
chatManager
  .connect()
    .then(currentUser => {
4
5
6
7
8
9
10
11
      currentUser.subscribeToRoom({
        roomId: currentUser.rooms[0].id,
        hooks: {
          onNewMessage: message => {
            console.log(`Received new message: ${message.text}`)
          }
        }
      });
12
13
14
15
    })
    .catch(error => {
      console.error("error:", error);
    })

Now, if you send a message from the Inspector tab of the dashboard, you’ll see it in the console:

Watch this as well - if you run the app again, you’ll see that onNewMessage is called retroactively up to 20 times.

In practice, this allows you to easily show your user recent messages.

Don’t want to show old messages? Set messageLimit to 0 in the object passed to subscribeToRoom. Chatkit is completely flexible by design.

1
2
3
4
5
6
7
currentUser.subscribeToRoom({
    roomId: currentUser.rooms[0].id,
    hooks: {
      onNewMessage: message => {
        console.log(`Received new message: ${message.text}`)
      }
    },
8
    messageLimit: 0
9
})

Send Your Own Message

Again, almost all interactions happen on the currentUser.

To send a message, we call currentUser.sendMessage with the ID of the room that we want to send the message to and the content of the message (the text).

1
2
3
4
currentUser.sendMessage({
  text: "hello",
  roomId: rooms[0].id
});

In this case, we're just sending the text "hello" but Chatkit also supports file attachments. Sending photo, video, and audio messages has never been easier.

Throwing It All Together

When you throw it all together with a simple form, you end up with this:

Here’s the complete code you to get something that works in the same way as the demo above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<html lang=en>
  <head>
    <meta charset=utf-8>
    <title>Chatkit demo</title>
  </head>
  <body>
    <ul id="message-list"></ul>
    <form id="message-form">
      <input type='text' id='message-text'>
      <input type="submit">
    </form>

    <script src="https://unpkg.com/@pusher/chatkit@0.7.5/dist/web/chatkit.js"></script>
    <script>
      const tokenProvider = new Chatkit.TokenProvider({
        url: "YOUR TEST TOKEN ENDPOINT"
      });
      const chatManager = new Chatkit.ChatManager({
        instanceLocator: "YOUR INSTANCE LOCATOR",
        userId: "YOUR USER ID",
        tokenProvider: tokenProvider
      });

      chatManager
        .connect()
        .then(currentUser => {
          currentUser.subscribeToRoom({
            roomId: currentUser.rooms[0].id,
            hooks: {
              onNewMessage: message => {
                const ul = document.getElementById("message-list");
                const li = document.createElement("li");
                li.appendChild(
                  document.createTextNode(`${message.senderId}: ${message.text}`)
                );
                ul.appendChild(li);
              }
            }
          });

          const form = document.getElementById("message-form");
          form.addEventListener("submit", e => {
            e.preventDefault();
            const input = document.getElementById("message-text");
            currentUser.sendMessage({
              text: input.value,
              roomId: rooms[0].id
            });
            input.value = "";
          });
        })
        .catch(error => {
          console.error("error:", error);
        });
    </script>
  </body>
</html>

Next Steps

The quick start is aimed at teaching you the key components of Chatkit. You learned about instances, rooms, users, and authentication.

What would you like to learn more about?

Did you find this document useful?

We are always striving to create the most accurate and informative docs as possible. If there is something especially wrong (or right) here then please let us know.