Today we will be looking about developing a chat application in nodejs using web sockets . Most people know what web sockets are. Many of us use chat programs like whatsapp , viber. Web sockets are used to create such applications ( real time applications) . Web socket are a full -duplex, TCP connection. We will be looing about using web sockets & nodejs. When using a web socket service with nodejs the best library to use will be Initially, we create a nodejs project by using “npm int” command.  After that, install express.   Express will be used to develop this server. . I will use  “npm i express –save”.    Next, install library.    “npm i –save”.  And let’s just make a public folder.  We need it in the future.  .    First goal is to create the index.js file.  Some of those can even server  js file.   It depends on how you command the “npm init” command at the entry point .

nodejs -entry point

I did not give a name so the default name is index.js.  Now if you look at your project, we will find a new files. First let’s get start from the index.js file . First of all, we require express in it

var express = require('express');

var app = express();
Now we need var socket = require(''); We need to assign a port to the server. In nodejs  we often run on a port like 4000, 8080. Let's run the nodejs server at 4000.  For that,
var server = app.listen(4000, function(){

console.log('listening for requests on port 4000,');


If you run node index.Js you should see the followings:

nodejs setup

Now command the  “node index” command and run the project. Then the terminal “Leaving for Regions on Port 4000” is shown.
For web sockets in nodejs we will be using Now, let’s start working with First of all, the needs to run for the same 4000 itself (Express run port).  We only used an express here. If we need to listen socket io by requiring http to the http server , we have to inform to listen to express because we have express in this. We use nodejs as a back-end. If we only use angular , reactjs , vuejs as front-end , we need http to work with socket io. This is a simple application that does not require a http request, we will not use it. Now add this line to index.js

var io = socket(server); // listen to the express running port

Now we need to understand the function of this,

socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender'game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender'message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client

We use only some of the functions.  Open    “io.on(event , callback)”//   port to the connection. First, we need to make sure that we have a new client connected.  To do so, It is necessary to write such a function ,


          console.log(‘new client has connected’,


This “new client has connected”  function didn’t displayed when we restarted this function on index.js. For that the client side should be inform that a client is join. We’ll see how to do it next.

READ  Facebook's cryptocurrency Libra: All you need to know

Now we need the public folder that we have created. Inside this we need to create both the chat.js file and  index.html file. For this we simply use a little css. Let’s make it a bit beautiful .Then we create a styles.css file in that public folder. Just remember, we do not use css for html tags here. We use the tag id. Because we use javascript to client side .. So we use   #html_tag_id to apply css instead of  html _class_Name.

Go to Google Search to get the above cdn. Through cdn go to this page and download the top link.  Let’s make a new connection over the chat.js file .

web sockets

Our is being listen by a server. That means Port 4000 is now listening the So, let’s make this new connection.

var socket = io.connect(‘http://localhost:4000’); Now if there is no problem, save the chrome files and restart the server . Now you will see the message, “The new server is connected” , and the new client’s socket ID (socket id, we do not currently need)  You need to know  how   “getElementById(id)’ , innerHtml , addEventListener() ” functionality of  “JS” works, at this step. Use these  functions to your chat.js

var message = document.getElementById('message'),

      handle = document.getElementById('handle'),

      btn = document.getElementById('send'),

      output = document.getElementById('output'),

      feedback = document.getElementById('feedback');

We are going to set the event listner to the button .When we click the button,  the values ​​of the “massage”  variable in the “handler” file moves to the server. Each time the button change username is clicked, the client will send an event with the new value. We also need a socket.emit ( ) function to do that. Because it pass data from sender to another receiver .

btn.addEventListener('click', function(){

    socket.emit('chat', { //this ‘chat’ name , event name is very import when we implement     this socket call in backend

        message: message.value,

        handle: handle.value


    message.value = ""; //finally clear all message value


This above event name “chat” is very important to us. I will tell it later.

READ  The Microservices Architecture

Let’s go to index.js.

Let’s send the sender’s message. We’re going to see what back-end is doing for it.  We need to inform to send the data from the event to the all online clients. This function should writes in index.js, which we previously wrote in io.on ( ).

io.on('connection', (socket) => {

    console.log('made socket connection',;

    socket.on('chat', function(data){

        io.sockets.emit('chat', data);



We need to show the message on the client side. We use “socket.on (event, callback)” to do that. This means that you show these details, indicating that the client’s chat will show up on the client’s side of the page

socket.on('chat', function(data){

    output.innerHTML += '

' + data.handle + ': ' + data.message + '



Take this line above index.js . This is about the static data in the public folder. I do not know much about that  app.use(express.static(‘public’));

Okay, now the work is over.  Let’s run this ,

Here is the final result of our chat app:

nodejs chat app

If  you notice applications like WhatsApp  and sites like Facebook shows the notification when a person sitting next to us is typing something in the message box. Here we are going to implement the same using

Now we are going to put an event listener to the message field. We are going to check by using js, whether or not the client is typing .

message.addEventListener('keypress', function(){

    socket.emit('typing', handle.value);


Broadcasting means sending a typing event to all connected clients . If you want to send a message to everyone except for a certain socket, we have the broadcast flag. This function should also be written to the socket connection that you have created.

socket.broadcast.emit(‘typing’, data);

This means that this data is emitt to others except the sender.

 socket.on('typing', function(data){

        socket.broadcast.emit('typing', data);


Let’s look at the front end of the page.. how can we show this typing message to the client? Let’s   write a little function in chat.js using socket.on () ..

socket.on('typing', function(data){

    feedback.innerHTML = '

' + data + ' is typing a message...


But when we type one typing, it’s show the message that “is typing” continuously . Will it be efficient to do that on every keyup? How do we handle such situation? . To  take it out,

feedback.innerHTML = '';//when stop writing

Put the line socket.on(‘chat’,function(data){}) on to the function of chat.js.

socket.on('chat', function(data){

    feedback.innerHTML = '';//when stop writting

    output.innerHTML += '

' + data.handle + ': ' + data.message + '


Lastly, chat.js should be:

READ  Custom React Hooks with GraphQL

nodejs chat code

The last index.js should be:


So, hope you were able to get a good understanding on how web sockets could be used with nodejs if you want to develop a chat application.