Build a real-time chat app with vuejs, socket.IO and Nodejs
Tags: backend, javascript, node, vue
Published: 2019-06-19 11:02:08

---
title: Build a real-time chat app with vuejs, socket.IO and Nodejs
published: true
tags: Backend,javascript,Nodejs,vue
canonical_url: https://masteringbackend.com/posts/build-a-real-time-chat-app-with-vuejs-socket-io-and-nodejs?id=33
---

Following my previous tutorials on [Vue.js for backend developers](https://dev.to/kaperskyguru/vue-js-for-backend-developers-2637-temp-slug-363951) where i listed out important things a [backend developer](https://dev.to/kaperskyguru/top-5-backend-frameworks-3oml-temp-slug-2451065)needs to learn in Vue.js, so i decided to make use of some of the listed items to create a production-ready and real-time chat application.

In this article, I will be showing you how I build a real time chat app with VUEJS, NODEJS and EXPRESS and SOCKET.IO.

Here is a screenshot of what we’ll build:

_N/B: Am not a front end guy, so don’t laugh at my design yet, colors and designs are my enemies am walking hard to befriend them. This is just to demonstrate though._

![](https://codelikemad.com.ng/wp-content/uploads/2019/04/WhatsApp-Image-2019-04-01-at-10.47.11-AM.jpeg)<figcaption>What we will be building.</figcaption>

**SETUP**

Node.js and NPM is required in this tutorial, if you don’t have NodeJS installed already you can install from here.

- A basic knowledge of JavaScript is required. 

- Also, little or no knowledge of VUEJS is required.

If everything is all set up, let’s get started.

 Create a directory for the application, open the directory with your favorite editor, I’m using visual studio code.

You can use the terminal, if you wish.

```
         mkdir ChatApp && cd ChatApp && code .
```

Next, let’s initialize the directory with NPM.

```
         npm init
```

When prompted to fill in some information, go ahead or press enter for default options. The information will be used to set up your package. json file.

**DEPENDENCIES INSTALLATION.**

Let’s install our application dependencies. I will drop a list of needed dependencies and how to install them. We will keep it simple and only install these two dependencies.

i. **EXPRESS**

```
         npm install express --save
```

ii. **SOCKET.IO**

```
        npm install --save socket.io
```

After installing all the dependencies, run

```
npm install
```

It’ll install all the required packages.

**FRONT-END WITH VUEJS (MARKUP)**

In the front-end, we will be using Vue. j’s, let’s move to installing Vue. is on our directory and also bootstrap 4.3.1

Create an index.html file.

```
         touch index.html
```

To include Vue. j’s and bootstrap in our projects we’ll just copy the CDN and include in the script section of our _index.html_ file.

{% gist 

https://gist.github.com/Kaperskyguru/739f35ecf5b7d2c23017d498cff457f9

%}

After installing Vue and bootstrap successfully, let’s move down to creating the markups with Vue and bootstrap.

{% gist

https://gist.github.com/Kaperskyguru/5317d37d122e18b950f932a93ea1d952

%}

To connect Socket. IO server to the client, we’ll add the Socket. IO client-side JavaScript library.

```
         <script src="/socket.io/socket.io.js"\>\</script\>
```

That will be our cue and bootstrap (HTML) file for the front-end. You can grab the entire code for the front-end here to follow along.

>           The best way to learn is to follow along

You can [download the client-side Socket.IO library here](https://github.com/socketio/socket.io-client) as well.

It’s up to you to do separation of concerns by separating the JavaScript codes from the markups, but in my case, I will include them together for easy access.

**SETTING UP OUR SERVER.**

Create a _server.js,_ inside the _server.js_ file, let’s create and configure the express server to work with Socket.IO.

{% gist

https://gist.github.com/Kaperskyguru/e7d318e4b57c61f662880a6ea411c6f3

%}

This is the basic configuration required to set up Socket. IO in the backend.

  **HOW SOCKET.IO WORKS**

Socket.IO is a JavaScript real time chat library,[you can read the documentation here](https://socket.io/docs/) since its outside the scope of this article, but I will try to explain a little that will be useful for this article.

Socket.IO works by adding event listeners to an instance of _http.Server_ which is what we are doing here.

{% gist

https://gist.github.com/Kaperskyguru/e7d318e4b57c61f662880a6ea411c6f3

%}
Next, we will listen for a new connection event.

{% gist

https://gist.github.com/Kaperskyguru/834061bfa752b785f662caa065ccf23a

%}

For example, if a new user visits 1_27.0.0.1:3000,_ the message in the _Console.log_ will be printed to the console.

The Socket.IO has many flags or methods we can call to perform many functions such as emitting an event, listening to events, etc., which we are going to make use of this article.

**Socket.ON():** Takes an event name and a callback as parameters, it listens for an event emitted from the server or vice versa, and the callback is used to retrieve any data associated with the event.

**Socket.EMIT():** This emits/sends an event with or without data to the listening sockets including itself.

**Socket.Broadcast.Emit()**: This emits an event to other connected clients without itself included. We will be using these methods to send different events from the server throughout the Chat App.

**SETTING UP OUR CLIENT-SIDE CODE**

Open up your index.html at the bottom part add the following code inside the script tag.

{% gist
https://gist.github.com/Kaperskyguru/b8ce6d9c3018fcc96cedee2d29ddab00
%}

We added the `var socket = io(); `and created a new Vue instance, also inside the newly created Vue instance, we set up our element with ` el: ‘#app’ `and also declared our data object with some empty arrays and properties.

Let’s move down to the` methods` _object,_ we can see a `Send() method `which stores our chat details into the message array and uses `Socket.emit() `flag to send a chat event to the server.

{% gist
https://gist.github.com/Kaperskyguru/c9ba489a771d31a8871ddfcabe365fc7

%}

At the server side, we receive the event with the `Socket.on()` flag and resend it back to other connected clients using the`Socket.broadcast.emit()` flag.

On the _vue `CREATED` hook_we listen to all the events emitted by the server, including the chat-message event we resent from the server earlier.

By broadcasting it, that means the server will send it to every other person connected to the server apart from the sender.

#### Analogy

So, if Mr. A sends the message to the server and the server re-broadcast it, Mr. B, C, D, E etc. will receive the message but Mr. A won’t because it’s the sender.

So, don’t worry even if we listen to the chat-message event on the CREATED object, we won’t receive our own message back from the server.

This is what we will do throughout the different user’s actions on the ChatApp.

With that out of the way, after receiving the event from the from the server in the CREATED Object, we will store it in our message array with `message type `(indicating it’s a message from the server) and the `user` (who sent the message).

{% gist
https://gist.github.com/Kaperskyguru/1a99f04f6bdf1a82d40f5d264d457b7f
%}

To summarize everything happening in the front-end part with each cue. Jews object, I will list and explain what is happening in each of them.

1. **Methods Hook:** In Vue.js, this is where all the methods/functions in your component are created, each time you call a method in the markup or template, Vue will look for it there.

 So far, we have only two methods declared viz:

i. **_Send():_** When a user types a message and click on the send button, this method is called to store the message in the message array with other detail and also emit an event to the server which I explain the process above.

ii. _**addUser()**_: The method emits the ‘joined’ event to the server and sets the ‘ready’ variable to ‘true’ showing the user has successfully joined the chat room.

{% gist
https://gist.github.com/Kaperskyguru/de9ad98b2b1b9eec70a4ac13055439c1
%}

**2. Created Hook** : In Vue.js, the created hook is called when the Vue.js component has loaded. So, this a good place to listen to all our events from the server.

We are listening to 6 events from the server and emitting 1 event to the server.
{% gist
https://gist.github.com/Kaperskyguru/93d9a74eb3c1976878ed199b4d914004
%}

From the code above, we should understand what each of them does, if not, use the comment section for questions.

**3. Watch hook:** The watch hook is a very interesting one, it can do a lot, but we used it to listen to changes on the message box and emit a _typing_ event which is being broadcast back to other clients by the server.

{% gist
https://gist.github.com/Kaperskyguru/1dc1e93f05e8375b64726f186d362740
%}


And in the markups with used vue.js directives to markup our view. Take a look at the full index.html file.

{% gist
https://gist.github.com/Kaperskyguru/c6ff199bc368ff5de37bb8c5f82d984a
%}

Congratulations for getting here. [You can subscribe to my channel](http://bit.ly/multimegaschool) to be notified when the video drops.

### Conclusions

Also, you can improve the code, add authentications, add groups, one to one chat and add database management to manage all your new changes with session management too.  I will be super excited to see your application.

I hope you learnt something new with Vue, Node, Express, and Socket.IO. [The full code is on GitHub, get it now.](https://github.com/Kaperskyguru/ChatAppWithVue_Socket.io)

Thank you for reading my article. Here at my [blog](https://bit.ly/multimegablog) or [medium](https://bit.ly/mymediumprofile) I regularly write about backend development, digital marketing and content management system. To read my future posts simply [join my publication](https://bit.ly/mymediumpublication) or click ‘Follow’ Also feel free to connect with me via [Twitter](http://twitter.com/kaperskyguru), [Facebook](https://facebook.com/multimegaitschool), [Instagram](https://instagram.com/kaperskyguru).

_If you are interested in backend development (or you’re internet enthusiast) both (Mobile | Web | Desktop) videos subscribe to my [Youtube channel](http://bit.ly/multimegaschool)_, we will be posting a collection of help full tutorials and guides like this one for artisans.

If you enjoy this post, make sure to let us know and share it with your friends and subscribe to my growing [channel](http://bit.ly/multimegaschool).

Sharing is caring.

The post [Build a real-time chat app with vuejs, socket.IO and Nodejs](https://masteringbackend.com/posts/build-a-real-time-chat-app-with-vuejs-socket-io-and-nodejs?id=33) appeared first on [Masteringbackend](https://masteringbackend.com).