Implement Stream Chat with Vanilla JS

...

In this post, we are going to implement a simple Group Chat application with Vanilla Javascript and Stream Chat!

Stream Chat allows you to rapidly ship real-time messaging systems that are reliable and robust, without the overhead cost and time of managing the infrastructure by yourself. And it’s pretty easy to use...

You’ll find out how easy it is to plug in a messaging module (with all the cool features) to your existing application or to build something new and exciting with the Stream SDK/API from a simple chat application to something even more complex, and you don’t have to worry about building all those functionalities yourself!

Let’s get started!

Create an Account on Stream

Creating an account on Stream is pretty straight forward.

Visit the Stream website and Sign up:

Once your account is created successfully, you can quickly log in to your dashboard to get your app secret and key as shown below:

You'll need the API key and secret to authenticate with the Stream API. Keep it safe 🙂

Set Up

Let’s set up the application structure by creating some directories and installing Stream...

To create your working directory and move into that directory, run:

Loading code sample...

Then make your directory to look like what we have below:

    ├── dashboard.bundle.js
    ├── public
    │   ├── index.html
    │   └── static
    │       ├── login.css
    │       └── style.css
    └── src
        ├── Dashboard
        │   └── index.js
        └── Utils
            └── config.js

Let’s start with the UI!

We are going to use the following html template for our chat application; add this template to your public/index.html file:

Then, download this CSS file and add it to the /public/static/index.css file.

Now, you should have the UI up and running, but it doesn’t do anything. It’s just a dumb HTML and CSS web page:

So, let’s get Stream to add some functionality to the html page!

Did you notice that we are loading a bundled version of our javascript file to the HTML page?

Loading code sample...

That’s because we're using the Stream Chat NPM module! So, we are going to install Stream Chat with NPM or yarn and then use browserify to bundle everything into dashboard.bundle.js.

You can install browserify globally; it’s not required for your application to work, it’s a tool to help us bundle npm modules and use them in the browser:

Loading code sample...

So, in your root directory (chat-application), run:

Loading code sample...

Now, we are all set up! Let’s get coding 🙂

To prepare, open the dashboard index file src/Dashboard/index.js; this is where we’ll write our chat logic.

└── src
    ├── Dashboard
    │   └── index.js

Group Chat Code

Add the code below to the src/Dashboard/index.js file:

Loading code sample...

And this to the src/Utils/configuration.js file:

Loading code sample...

Now, let’s dig into the code and see how it all comes together...

Right here, we are importing Stream and importing the chatbubble template, which we defined in the config file:

Loading code sample...

The BubbleTemplate is a function that returns HTML when we pass the name, id, text, date, and the image url of the bubble. We need this bubble template because each time we receive a message from the group, we want to push it to the UI as a bubble containing a message in a group chat. We can easily pass the message object info to this function and re-use it as many times as we want to:

BubbleTemplate(name, id, text, date, image)

Next, let’s select the message input field and define some important information:

Loading code sample...

In reality, the token should be generated after you log in/create a user for your Stream application using the Stream API. You can start by using this open-source Stream API to log users in.

Run this command in a different directory to clone the open-source API and install the dependencies:

Loading code sample...

The API uses MongoDB to store user data; create a MongoDB database with Mongo Atlas and get your MongoDB URI. Then, get your API Secret and Key from your Stream Dashboard, as explained earlier.

Create a .env file in the root directory of the API and add the following configuration to it:

Loading code sample...

Then, run

Loading code sample...

to start up the API; it should be running on the PORT=8080, as defined in the .env file.

You can now create a user using Postman by sending a POST request to this url http://localhost:8080/v1/auth/init, with this data:

{
  "name": {
          "first": "First Name",
          "last": "Last Name"
  },
  "email": "foo@bar.baz",
  "password": "qux"
}

Copy the token and apiKey, and user id from the response. Switch back to your chat application src/Dashboard/index.js file we’ve been looking at and update the token and apiKey with the token and key from the response:

Loading code sample...

It would be fun if you can create a registration interface to make an api call to this api and store the data in local storage after registration...

You can start with something like this:

Loading code sample...

and an html sign up page like this:

Loading code sample...

That’s like a pretty good starting point...

So, now that we understand what is going on here:

Loading code sample...

Let’s move on to the next bit of code!

Setting A User

Setting a user in Stream Chat is pretty simple. Create a new instance of StreamChat called client by passing in your API key to the constructor. This will serve as an entry point to access the StreamChat functionality.

Next, we initialize a new user. You can get all the information you need to set a user in the response you receive from the API call you made initially:

Loading code sample...

Set The Channel Details And Subscribe to Further Updates

So, what channel do you want your users to be in? You can specify the channel information in the channel.client function. The channel receives three parameters. The first is the channel type (we'll use 'messaging'), and the other are the channel ID and details you can specify as many details as you want):

Loading code sample...

Send a Message to The Group

Next, we'll plug in an event listener to the messageInput (the input box you type your messages into) that we defined initially.

We'll listen to your key presses with the checkTyping function and let everyone know that you are typing:

Loading code sample...

and when you finish and hit enter, we'll catch that using the keyCode 13, and then send the message with channel.sendMessage:

Loading code sample...

Listening For New Messages

If any member of the channel sends a message, we get notified using the message.new event. We look at the messages in that channel state and pick the latest message and push it to the UI.

Loading code sample...

Loading Historical Messages

The first time we open our app, the first thing we want is to load our previous conversations so we can start up from there...

That is what this part of the code does. It gets the state data, and pushes it to the UI:

Loading code sample...

Last, but not least, let’s talk about the singleMessageDisplay function; this function just stacks the latest messages (using the bubble template) to the UI. If the message is from you, it stacks it to the right, and if it’s from anyone else in the group, it stacks it to the left:

Loading code sample...

So, far here is what we have:

Our application is ready! Here is how the final chat application works:

You can find the completed project on Github here.

A Few Notes

I'd advise using browserify to bundle your javascript code like so:

Loading code sample...

Wrapping Up

Creating a chat application with Vanilla Javascript and Stream is pretty simple, and there is so much more you can do with Stream, this is just scratching the surface...

Check out the docs to learn more! I challenge you to add even more functionalities to the chat application after reading the docs...

I can’t wait to see the awesome stuff you’ll build with Stream and Javascript!