Following my previous tutorials on Vue.js for backend developers where i listed out important things a backend developerneeds 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.
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.
After installing Vue and bootstrap successfully, let’s move down to creating the markups with Vue and bootstrap.
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 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.
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 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.
Next, we will listen for a new connection event.
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.
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 themethods
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.
At the server side, we receive the event with the Socket.on()
flag and resend it back to other connected clients using theSocket.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).
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.
- 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.
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.
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.
And in the markups with used vue.js directives to markup our view. Take a look at the full index.html file.
Congratulations for getting here. You can subscribe to my channel 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.
Thank you for reading my article. Here at my blog or medium I regularly write about backend development, digital marketing and content management system. To read my future posts simply join my publication or click ‘Follow’ Also feel free to connect with me via Twitter, Facebook, Instagram.
If you are interested in backend development (or you’re internet enthusiast) both (Mobile | Web | Desktop) videos subscribe to my Youtube channel, 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.
Sharing is caring.
The post Build a real-time chat app with vuejs, socket.IO and Nodejs appeared first on Masteringbackend.
Top comments (0)