Back to all blogposts tutorial: Real-time communication in web development

Mateusz Piguła

Mateusz Piguła

Frontend Developer

There are a few ways of building a tool for real-time communication. Two of the most popular approaches presuppose the use of HTTP Long Polling or WebSockets. In the article below, you’ll find a brief comparison of both solutions. I decided to focus on the latter solution a little bit more. That’s why in the article, you’ll find a straightforward tutorial for building a real-time chat.

What are WebSockets?

WebSockets are quite an interesting technology in and of itself. Let’s take a closer look at what it is.

WebSocket definition

WebSockets API is a technology providing a bidirectional communication channel between a client and a server. That means that the client no longer needs to be an initiator of a transaction while requesting data from both the server and database.

How do WebSockets work?

Typically, the client requests data starting a new connection and then the client loses connection. The server sending data also only has connection during the exchange. With WebSockets, during the first request to the backend server, except receiving incoming data, the client also establishes an initial connection. This process is known as the WebSocket handshake. 🤝 The Upgrade header is included in the request. That’s how the client connected informs the server that it needs to create a connection.

See also: A few simple tips on how to create WebSocket API in Node.js

WebSockets vs HTTP

So, does it mean it’s impossible to create a chat application without WebSockets? 😨

Well, there is a technique called HTTP Long Polling. Using this, the client sends a request and the server holds that opened until some new data is available. As soon as data appears and the client receives it, a new request is immediately sent and operation is repeated over and over again. However, a pretty big disadvantage of using HTTP Long Polling is that it consumes a lot of server resources. 😥

Are you ready to talk to your clients?

👨‍💻 Work with software development professionals who build scalable apps for big companies such as eSky, StageClip, or Reservix. Ranked as Poland’s top software house by Clutch. chat room app tutorial – building a chat app 🚀

Below, I’ll present to you a brief tutorial on how to create a simple chat application with Vanilla JS frontend part and Node.js server. The Socket io library is a JavaScript library that enables real-time, bidirectional, event-based communication between the connected clients (browser) and the server side.

You need to create a project with the default package.json file.

A screenshot with some code for purposes of tutorial

Having this created, you need to set up a server and install all the needed dependencies. In order to do it, you need to create an index.js file and install and express. You can use the following command: touch index.js && npm install express && npm install --save-dev nodemon.

In index.js, you need to set up a local server and basic socket connection. 

And basically, that’s all you have to do on the backend side at the moment. Once you make a proper request, the connection should be established. It will be visible through the logged message (as shown below).

Now, you need to prepare the frontend part.

Let’s start by creating the public folder and the following files: index.html, main.js. Optionally, you can add style.css

Below, you can see the index.html scaffold. Basically, all you need are HTML tags you can refer to and some scripts from included in the project. That’s how your index.html file should look with the WebSockets scripts included.

Then, you need to set up the connection on the frontend side. The only line of code you need in main.js is const socket = io();.  It’s shown in the video below.

As you can see – once the page is opened and the script is loaded, the connection is established. The next thing you need to do is to handle a new user connection, a new message and, last but not least – a currently typing user.

See also: Strapi: Getting started with the Node.js headless CMS

In socket, there are two ways to emit data such as events. One way is from the user to everyone (including user) and the other which emits an event to all the other instances. The idea is to display the list of all the active users. So, when a user connects – they need to inform about it and get the list of users who are already active.

When a user connects – they emit the event which includes the information about their username. You should set the property of userId on the socket. It will be needed when the user disconnects. To do that – you need to add a username to the Set of active users and emit an event with a list of all active users.

In the main.js I created two functions and two socket listeners.

Firstly, I created a new user (you can easily extend functionality by adding some prompt with a real user name) and emit an event with that username. Also, I added them to the sidebar with all active users. When a user disconnects on the server side – they are removed from the Set of active users and a disconnection event with their username is emitted. After that – they are removed from the sidebar on the client side (as you can notice on the short video below).

Since we handled the way users can connect and disconnect, now it’s time we handle the new messages.

On the server side – you do nothing more than adding the listener shown below.

On the client side – you need to do a few more things, as per the example below.

The function responsible for displaying new messages is triggered right after receiving information from a socket. The message is pushed to the server in the listener function of the form submit. You just need to check if the client is a message author or not. tutorial screenshot showing an example of a simple chat app


Now, I will show you how to emit the event responsible for informing all other connections except yours. We want to display info that a user is typing something at the moment.

On the server side, you need to add socket.broadcast.emit. Take a look below (it is the final version of the file).

On the client side, you need to take a look at inputField keyup event listener and socket listener on typing. Below, you can see both things and the final version of main.js.

And the final effect is presented in the video below. 🙌

See also: Horizontal scaling with WebSocket – tutorial chat app summary

As you can see, building a chat app (or any other web apps for that matter) equipped with basic chat messages features using is not difficult. I hope that this brief tutorial helped you understand just how simple using this approach is. And how many interesting things you can do with JavaScript and basic Node.js knowledge.

There are plenty of app ideas based on WebSockets. You can create: 

  • an app that streams matches of your local sports team. You can stream games in the text version or video if possible (or maybe both? 🤔)
  • multiplayer game for you and your friends 🎮
  • secret chat available only for your group 🙊
  • app based on GPS, maybe a game that uses location? 🌏

I always strongly encourage you to learn more about other related concepts related to such as socket namespace, socket object, state variable socket, client, io server export default app, the message bus or broadcast flag. With that, you can create much more complex apps with multiple data points.

Your imagination is the limit!

You may also like

What would you like to do?

    Your personal data will be processed in order to handle your question, and their administrator will be The Software House sp. z o.o. with its registered office in Gliwice. Other information regarding the processing of personal data, including information on your rights, can be found in our Privacy Policy.

    This site is protected by reCAPTCHA and the Google
    Privacy Policy and Terms of Service apply.

    We regard the TSH team as co-founders in our business. The entire team from The Software House has invested an incredible amount of time to truly understand our business, our users and their needs.

    Eyass Shakrah

    Co-Founder of Pet Media Group


    Thank you for your inquiry!

    We'll be back to you shortly to discuss your needs in more detail.