A Guide To Develop Real Time Apps With Node.js

Real time apps with node.js

We have been using lots of mobile applications to carry out day to day tasks. So building applications that users can interact with in real-time has become a standard for many developers. The applications that today we use whether they are mobile, web or desktop apps have at least one real time feature. Mostly real-time messaging and notifications are the commonly used real-time features that we use in applications. 

What Do Real Time Applications Do?

As mentioned before, real time applications functions within a time frame the user feels it is occurring in real time. Within real-time applications or real-time computing, the latency is set under a defined value, typically estimated in seconds.

Know the important points to consider while developing real time apps at- What To Consider While Developing Real Time Applications?

Role Of Node.js In Real-Time Applications-

Node js helps with its non-blocking I/O and event-driven features to the applications where speed and scalability are constant focus. Nodejs gives continuous two-way connections to applications like social media, forums, ad servers, or stock exchange software.

1. Reusing And Sharing-

Nodejs supports microservices architecture and it allows developers to reuse the library code package and share it in various projects. It not only saves development time and increases productivity.

2. Scalable And Rapid-

As Node Js is javascript based, it executes rapidly like JS. So an application with event loop easily handles multiple client requests.

3. Event Based Server-

Real time apps handles a large number of real-time users. Node.js development supports response based on the event-driven server that supports non-blocking functioning.

4. Proxy Server-

Node js will be your best choice where intermediary administrations are necessary. To use node.js server as a proxy server, a developer needs to add a code of 20-line, and your application will turn into an ideal fit to support streaming information from numerous sources.

5. SEO Friendliness-

The backend rendering by Node.js gives the website more visibility and engagement too. The applications get more speed and user experience as well as a get performance that is required to rank according to SEO prospects defined by Google.

Building A Real-Time Chatroom With Node.js-

Here we’ll see how to build a simple chatroom that users can use to communicate  with connected users. With this, multiple users can connect to the chatroom and users can send messages that will be visible to all users connected to the chatroom.

Features of simple chatroom-

  • Change the username of the user
  • Send messages
  • Show if another user is currently typing a message

Application Environment Setup-

  1. Create directory
  2. Run the npm init to set up package.json file.

Install Dependencies-

Here we’ll use express, ejs, socket.io and nodemon packages to build app.

  • Ejs- It is a well known JS template engine

Command to install ejs- npm install express ejs socket.io –save

  • Nodemon- This package restarts the server every time we make any change to the application code. Due to the use of Nodemon you don’t need to manually stop and start the server every time when you make change. Command to install Nodemon
npm install nodemon --save-dev

Add a start script to your package.json file to start the application with nodemon. 

"scripts": {
"start": "nodemon app.js",
 },

Use the following command to start app-

npm run start

Set Up The Application Structure-

With all the Dependencies that will need for this project installed, build app project structure. For this, you have to create some directories. Get that done so that your app structure look like

|--app.js
|--views
|--node_modules
|--package.json
|--public
|--css
 |--js
  • app.js: file we will use to host our server-side code
  • views: folder containing the views (ejs)
  • node_modules: where we installed our dependencies
  • package.json npm configuration file
  • public: directory we will use to store our assets, like css files, javascript files (for the client side), and images.

Step 1: Build Server-

It is necessary to get express up and run. For this open app.js file and paste the code as follows:

const express = require('express')
const socketio = require('socket.io')
const app = express()
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.get('/', (req, res)=> {
    res.render('index')
})
const server = app.listen(process.env.PORT || 3000, () => {
    console.log("server is running")
})

Now start working on the sockets.io initialization. Add the following code at the end of app.js file.

//initialize socket for the server
const io = socketio(server)

io.on('connection', socket => {
    console.log("New user connected")
})

If you now run your server with npm start you will have the option to receive new socket connections. So let’s build a front-end.

Step 2: Build Front-End-

Create a template in views folder, and for this create index.ejs file and paste the below code:

<head>
    <title>Simple realtime chatroom</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div class="title">
            <h3>Realtime Chat Room</h3>
        </div>
        <div class="card">
            <div class="card-header">Anonymous</div>
            <div class="card-body">
                <div class="input-group">
                    <input type="text" class="form-control" id="username" placeholder="Change your username" >
                    <div class="input-group-append">
                        <button class="btn btn-warning" type="button" id="usernameBtn">Change</button>
                    </div>
                </div>
            </div>
            <div class="message-box">
                <ul class="list-group list-group-flush" id="message-list"></ul>
                <div class="info"></div>
            </div>
            <div class="card-footer">
                <div class="input-group">
                    <input type="text" class="form-control" id="message" placeholder="Send new message" >
                    <div class="input-group-append">
                        <button class="btn btn-success" type="button" id="messageBtn">Send</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <script src="/js/chatroom.js"></script>
</body>
</html>

Note how we have included the script of the client-side socket.io library and the custom javascript file we are going to use in this code.

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script src="/js/chatroom.js"></script>

We have added a button with ID messageBtn to send a new message and button with ID usernameBtn to submit new username. All user messages will appear in the unordered list with ID message-list. If a user is typing a message, it will appear inside the div with class info. Now the buttons are static. Let’s connect the front-end to the server.  Create a new Javascript file named chatroom.js inside the js folder of the public directory. Inside Javascript file, we have to connect the socket from front-end.

(function connect(){
    let socket = io.connect('http://localhost:3000')
})()

Step 3: Send Message-

Now we implement the send message feature. First, we will set up the front-end to emit a new_message event when a new message is submitted. Since the client-side should also be configured to get new messages other users send from the server, the application should also listen to receive_message events on the front-end and show the new message on the web page properly.

We can get done both these tasks using the following code-

let message = document.querySelector('#message')
let messageBtn = document.querySelector('#messageBtn')
let messageList = document.querySelector('#message-list')
messageBtn.addEventListener('click', e => {
    console.log(message.value)
    socket.emit('new_message', {message: message.value})
    message.value = ''
})
socket.on('receive_message', data => {
    console.log(data)
    let listItem = document.createElement('li')
    listItem.textContent = data.username + ': ' + data.message
    listItem.classList.add('list-group-item')
    messageList.appendChild(listItem)
})

Each time the receive_message event occurs on the client side, we change our DOM to deliver the message into the screen. On the back-end side, when you receive a new_message event, you have to emit a new event to all clients. For this, use io.sockets.emit().

Change connection event in app.js file as follows:

io.on('connection', socket => {
    console.log("New user connected")
    socket.username = "Anonymous"
    socket.on('change_username', data => {
        socket.username = data.username
    })
    //handle the new message event
    socket.on('new_message', data => {
        console.log("new message")
        io.sockets.emit('receive_message', {message: data.message, username: socket.username})
    })
})

At the time of handling new_message event, server emits a receive_message event to connected users.  This event is received received by all users connected to the server, so that new messages are displayed on their chatroom interfaces.

Step 4: I’m typing-

For this, we add new event listener to the message input box to emit typing event when a keypress occurs. As keypress occurs on the message input box, it indicates user is typing a message, the typing event tells server that user is typing a message. The client side also listens to typing events emitted by the server to know whether another user is typing a message and show it on the UI.

Inside the connect function in chatroom.js, we add the following code.

let info = document.querySelector('.info')
message.addEventListener('keypress', e => {
    socket.emit('typing')
})
 
socket.on('typing', data => {
    info.textContent = data.username + " is typing..."
    setTimeout(() => {info.textContent=''}, 5000)
})

Final Words-

From all this, you can understand how to build real time apps with node.js. If you’re still confused, consult with solace experts. We have dedicated team of developers to help you through development. Connect with solace and get a free quote to develop effective real time apps. You can also hire node.js developers of solace team for an efficient and effective real time apps development. We will be happy to help you.

Related Post