In a world where the value of time is steadily increasing, most developers now build applications that users can interact with in real-time. Most applications today, whether mobile, desktop, or web-based, include at least one real-time feature. Real-time messaging and notifications, for example, are two of the most common real-time features used in applications.
We will introduce you to developing real-time applications using Node.js by creating a real-time chat. Although this article will focus on this specific use case, the concepts taught here can be applied to other scenarios.
Because of its event-driven and asynchronous nature, Node is one of the best programming languages for developing real-time applications. Before diving headfirst into building a real-time application, we’ll look at the types of applications that can be built with Node.js development company.
Where are Real-time Applications Used?
As previously stated, messaging and notification delivery are the most common real-time application use cases. However, real-time applications can be used for various other purposes, and let’s look at them.
Most of us are familiar with real-time messaging apps, particularly on mobile devices, such as Whatsapp, Facebook Messenger, and various other messaging apps. However, real-time messaging is not only used in messaging applications; On-demand taxi apps, delivery apps, and collaborative platforms all have real-time messaging features.
Real-Time Notification Delivery
When it comes to increasing user engagement with applications, enabling real-time notifications has proven to be a game changer. As a result, it is rare to find a modern application that does not provide real-time notifications to its users.
Live streams with real-time interaction are becoming increasingly popular since social media platforms integrated live video streams into their applications. The best examples are the live video streaming features on Instagram and Facebook.
With the introduction of popular taxi and delivery applications such as Uber and Amazon, real-time tracking of users’ taxi rides or deliveries has become a must. Their real-time progress updates enhance these applications’ usability and dependability.
IoT devices must have real-time capabilities. Data collected by sensors installed in IoT devices is transmitted, processed, and displayed to end users with minimal delay. Because the majority of the inputs captured by these devices, such as temperature and lighting change all the time, applications that work with IoT devices should be able to receive and send data in real time.
How Can We Build Real-Time Applications?
Is developing a real-time application different from developing a standard web application? Yes, the answer is yes.
Consider a messaging app that allows users to send messages in real-time. The messages should appear in the other user’s applications as soon as they are sent. Suppose we implement this application as a standard web application, where only the client can initiate requests to the server to receive data. In that case, the user must either regularly refresh the web page to see the most recent messages, or the client-side should send AJAX requests to the server in short time intervals to retrieve the most recent messages. The former is inconvenient for users, while the latter is a waste of application resources. Then, we must have a different method to build real-time applications that makes better sense.
WebSocket is the solution we require. WebSocket is a communication protocol that enables client and server communication. In other words, with WebSocket, the server can send data to the client at any time without requiring the client to first request data. In the previous messaging application, we could use WebSockets to send messages to all users instantly via the server. When developing applications, we can use the WebSocket API to communicate via WebSockets.
Building a Real-time Chatroom with Node.js
Now that we’ve covered the fundamentals of real-time application development, we can get started on building our own. In this tutorial, we will create a simple chat room where users can communicate with other connected users. Any number of users can connect to the chatroom, and any messages sent by one user are instantly visible to all users connected to the chatroom.
Our simple chatroom is going to have the following set of features.
- Change the username of the user
- Send messages
- Show if another user is currently typing a message
Cool, now that we have our requirements, let’s start building the environment and setting up the structure.
If you are looking for a UK based company for app development, reach out to applify.co.
Setting up Application Environment
First, create a new directory for the application. If you didn’t, don’t worry, you can always change it in your package.json at a later point.
- Install Dependencies
To build the application, use the express, ejs, socket.io, and nodemon packages.
- Ejs is a popular JS template engine.
- The use of socket.io
- Nodemon is a package that restarts the server whenever we modify the application code. It removes the need to manually stop and restart the server whenever we make a change. Unlike the other packages, we install nodemon as a development dependency because we only use it for development.
Use the following command to install express, ejs, and socket.io.
Using this command, add nodemon as a development dependency.
To run the application with nodemon, we need to include a start script in our package.json file.
The application can then be launched by issuing the following command from the command line.
Don’t worry if it fails because we don’t yet have a code file.
Set Up The Application Structure
With all of the dependencies for this project installed, let’s build the project structure. You’ll need to make a few directories and, for the time being, just one file called app.js. Let’s get that done, so your app structure looks like this:
We believe the structure is fairly clear, but let us go over it briefly:
- app.js: This is the file that will house our server-side code.
- views: the folder that contains the views (ejs)
- node modules: this is where we put our dependencies.
- npm configuration file package.json
First Steps Building The Server
Before we even think about making real-time connections, we need to get express up and run. To do so, open our app.js file.
We can begin working on the sockets.io initialization once we have configured express and used ejs as the template system. Add the following code to the end of your app.js file to accomplish this.
The code is simple; we initialize socket.io from our server connection (express), then set up an event using io.on() that will be triggered whenever a new connection is established.
You will now be able to receive new socket connections if you run your server with npm start. So let’s get started.
Building Our Front-End
We won’t spend much time making our front end look great, but we will explain how the server connection works, how to emit and capture socket events, and how to apply all of that to our chat example.
To begin, create a template in our views folder by creating an index.ejs file.
We also have ID messageBtn buttons for sending new messages and ID usernameBtn buttons for submitting new usernames. The username and message inputs IDs are username and message, respectively. All user messages should appear within the unordered list with the ID message list. If a user ties a message, that information will be displayed inside the div with class information.
Navigate to http://localhost:3000/ in your browser.
But it’s not doing anything, the buttons aren’t working, and it’s a static application. So, let’s begin by connecting the front end to the server.
Return to your website and your terminal (on the server side).
Awesome! Your app is already operational, albeit ineffectively. Next, let’s add some functionality.
Changing The User Name
We use “Anonymous” as the default username for all connections. We give users the option of changing their usernames. When the front end emits a change username event, we’ll configure the back end to change the username. Return to your server-side code (app.js) and modify your connection event to include the new code.
Next, we must modify our front end so that when we press the change username button, an event with the name change username is sent to the server. Have you noticed how we constructed the name by emitting and capturing the same event name?
Inside chatroom.js, we’ll add an event listener to usernameBtn so that when the button is clicked, it emits a change username event.
Now, if you reload the web page and submit a new username, you will see your current username changed to the new one. Next, let’s start sending messages.
The next feature we’ll add is the ability to send messages. Things begin to differ here; previously, we stated that every time the front-end emits a message, the server receives it; however, in our new case, the front-end must emit a new message event, which must then be sent to all connected clients so that they can print the new message.
To begin, we will configure the front end to fire a new message event whenever a new message is submitted. Because the client-side should be configured to receive new messages from the server, the application should also listen for receive message events on the front end and display the new message appropriately on the web page. We can accomplish both tasks by inserting the following code into the previous connect function in chatroom.js.
When the receive message event occurs on the client side, we modify our DOM to display the message on the screen.
When we receive a new message event, we need to emit a new event to all clients, so we use the io.sockets.emit() function. Change the connection event in your app.js file to:
When the server handles the new message event, it sends a received message to all connected clients with information about the new message. All users connected to the server, including the one who sent the message, receive this event, and the new message is displayed on their chatroom interfaces.
You can now start chatting (with yourself?:p) if you open your web app in your browser (you can have multiple instances).
You can connect to the chatroom using two different browsers and experiment with the messaging feature, seeing how messages sent by one user appear instantly on the application interfaces of both users.
Using real-time features with desktop, mobile, and web applications is almost a requirement nowadays. In this article, we discussed a variety of real-time applications and learned how to create a real-time chatroom using Node.js development service. To proceed, you can either try to improve this chatroom by adding more features and storing older messages in a database or implement another real-time application with a different use case.