Bacancy Bacancy
  • Customers

      Fortune 500 Clients

      Verizon
      Verizon
      Franklin Templeton
      Franklin Templeton
      The Container Store
      The Container Store
      KPMG
      KPMG
      Academy Sports & Outdoors
      Academy Sports & Outdoors
      Shell
      Shell
      Bangkok Bank Ltd
      Bangkok Bank Ltd
      The Children's Place
      The Children's Place
      Edward Jones
      Edward Jones
      United Parcel Service
      United Parcel Service
      AdviceWorks
      AdviceWorks
      NatWest Markets
      NatWest Markets
      Bridgestone
      Bridgestone

      Technologies

      React JS VueJS Angular JS React Native Flutter Full Stack
      Ruby on Rails Node JS Golang AI & ML Data Science Java
      Python Salesforce DevOps Block Chain Mobile App Embedded & Hardware
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • what we do

      Experience

      Digital Workplace Services Product Enhancement

      Insights

      AI & Automation Data Analytics

      Innovate

      Blockchain Software Engineering Services Internet of Things (IoT) Data Science Artificial Intelligence Machine Learning

      Accelerate

      Cloud - Bacancy Combalt Digital Process Automation Open Source Microsoft Dynamics Salesforce

      Assure

      Quality Assurance IT Staff Augmentation

      Embedded & Hardware

      Product Engineering Analog Design Services FPGA Engineering Service Wireless Design Embedded Software Design

      not list

      Hardware Engineering Power Engineering IoT Hardware
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • who we work with

      Industries

      Banking Financial services & Insurance Startups Oil & Gas

      not list

      Healthcare Life Science Real Estate & Construction Logistics
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • about us

      Culture

      Agile Mindset Bacancy Values Bacancy Culture

      About Company

      About Us Leadership Team Awards & Recognition Infrastructure

      not list

      Customer Reviews Our Locations Partnership Media Coverage

      WE ARE

      GREAT PLACE TO WORK - CERTIFIEDTM

      Building and sustaining High-Trust, High-Performance CultureTM

      Bacancy Great Place to Work
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • technology

      Front End

      Angular Reactjs Vue.js UI/UX

      Platforms

      MS Dynamics Salesforce

      Back End

      Ruby on Rails Node.js Golang Laravel .NET Java Python

      Mobile

      React Native Flutter Android iOS

      Cloud

      AWS DevOps

      QA

      Automation Testing Software Testing

      Embedded & Hardware

      Embedded
      bacancy

      World-class expertise,Delivered

      get quote
      Explore All
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
  • PRODUCTS

      EV Products

      Battery Management System Motor Controller AC Charger Explore All

      not list

      CCS2 Controller DC Fast Charger AC Charge Controller
      bacancy

      Let’s grow together Partner with us

      get quote
      skype-icon

      Skype ID

      bacancy
      gmail-icon

      Email Us

      [email protected]
      call-yellow-icon

      USA

      +1 347 441 4161
      wp-icon

      Canada

      +1 416 907 6738
hire developers

Bacancy

Bacancy represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.

12+

Countries where we have happy customers

1050+

Agile enabled employees

06

World wide offices

10+

Years of Experience

05

Agile Coaches

14

Certified Scrum Masters

1000+

Clients projects

1458

Happy customers

  • Customers
      Technologies
      • React JS
      • Angular JS
      • Vue JS
      • Node JS
      • AI & ML
      • Explore All
      Fortune 500 Clients
      • Verizon
      • The Container Store
      • KPMG
      • Academy Sports & Outdoors
      • Bangkok Bank Ltd
      • The Children's Place
      • Edward Jones
      • Franklin Templeton
      • AdviceWorks
      • NatWest Markets
      • Bridgestone
      • United Parcel Service
  • What we do
      Experience
      • Digital Workplace Services
      • Product Enhancement
      Insights
      • AI & Automation
      • Data Analytics
      Innovate
      • Blockchain
      • Software Engineering Services
      • Internet of Things (IoT)
      Accelerate
      • Cloud - Bacancy Combalt
      • Digital Process Automation
      • Open Source
      • Microsoft Dynamics
      • Salesforce
      • Service Experience Transformation
      Assure
      • Testing
      • Resource Augmentation
      Embedded & Hardware
      • Product Engineering
      • Analog Design Services
      • FPGA Engineering Service
      • Wireless Design
      • Embedded Software Design
      • Hardware Engineering
      • Power Engineering
      • IoT Hardware
      • AL/ML
  • who we work with
      Industries
      • Banking Financial services & Insurance
      • Startups
      • Oil & Gas
      • Healthcare Life Science
      • Real Estate & Construction
      • Logistics
  • About Us
      About Company
      • About Us
      • Leadership Team
      • Awards & Recognition
      • Infrastructure
      • Our Locations
      • Partnership
      Culture
      • Agile Mindset
      • Bacancy Values
      • Bacancy Culture
  • Technology
      Front End
      • Angular
      • Reactjs
      • Vue.js
      • UI/UX
      Platforms
      • MS Dynamics
      • Salesforce
      Back End
      • Ruby on Rails
      • Node.js
      • Golang
      • Laravel
      • .NET
      • Java
      • Python
      Mobile
      • React Native
      • Flutter
      • Android
      • iOS
      Cloud
      • AWS
      • DevOps
      QA
      • Automation Testing
      • Software Testing
      Embedded & Hardware
      • Embedded
      Explore All
  • Products
    • Battery Management System
    • Motor Controller
    • CCS2 Controller
    • AC Charger
    • DC Fast Charger
    • AC Charge Controller
    • Explore All
  • Careers
  • Work @ Bacancy
  • Blogs
  • Resources
  • Customer Reviews
  • Contact
  • Get Quote
Chat App with Express, ReactJS, and Socket.IO

How to Build Real-time Chat App with Express, ReactJS, and Socket.IO?

Archita Nayak
Archita Nayak Technical Writer
Last Updated on January 2, 2023
January 25, 2021 8 min read

I have always been very interested in learning how the live user interactions in real-time chat applications work? Such web applications always excite me to find the answer of how to build real-time chat app. To quench my thirst for knowledge, I started reading blogs and watching tutorials. After getting my hands on building a real-time chat app with Express, ReactJS, and Socket.IO, I decided to write a blog on it, as it was once said by Margaret Fuller, “If you have the knowledge, let others lit their candles in it.”

Table of Index

1. Overview

2. What is Socket.IO? And how does it work?

3. How to build the chat app with Express, ReactJS, and Socket.IO?

4. Conclusion

Overview

It might seem quite challenging when you read the topic – How to build a Chat App with Express, React, and Socket.io? This blog will surely take care of that challenge, and I’ll try my best to make it as simple as possible. So, let’s take the challenge and move ahead with a positive quote I read somewhere –

“We don’t grow when things are easy. We grow when we face challenges.”

Before starting the coding part, I would like to give some preliminary information about What is Socket.IO? You can skip this part and head towards the coding section if you’re familiar with Socket.IO already.

What is Socket.IO? And How Does it Work?

Socket.IO was developed for real time applications that can communicate and develop live user-interaction. As the documentation of Socket.IO states –

Socket.IO is a library that enables real-time, bidirectional, and event-based communication between the browser and the server.

With the help of Engine.IO, Socket.IO establishes the connection and permits bidirectional communication between client and server. The bidirectional communication takes place only when the client and server both have Socket.IO integrated. It transfers data in various forms, but the most likely in JSON format.

Socket.IO transfers data from the client of the particular server to the server, and then that server transmits it to other clients. This is how the transfer of information takes place.

I hope you now have a better understanding of Socket.IO. You can visit its documentation to start your Socket.IO tutorial. Finally, it’s time to build your own real time chat app.

Full-stack development services

How to Build a Real-time Chat App with Express, ReactJS, and Socket.IO?

I assume that you have Node.js V10 or higher version installed on your system. If not, then click here to install.

Starting with the basics

I’m creating here the main folder and then initiating it using NPM-

mkdir chat-app
cd chat-app

npm init

Setting up Express Server and Socket.IO

Once you click enter for all the options, install the Express library and Socket.IO for handling socket connections.

npm install --save express socket.io

After installing the Express and Socket.IO library, we will create a file to implement our new application’s logic.

touch server.js

Now we will write the express server code in the server.js file. Open your real-time chat-app and start editing it.

//server.js
let express = require('express')
let http = require('http')
let socket_IO = require('socket.io') 

const PORT = 8001 
let app = express() 
let server = http.Server(app) 
let io = socketIO(server) 

io.on('connection', (socket) => {
  console.log('User is connected sucessfully')
  
  socket.on('disconnect', () => {
    console.log('Sorry! User is unfortunately disconnected')
  })
})

server.listen(PORT, () => {
   console.log(`Running on port ${port}.`);
});

Now, by running the below-mentioned command, ensure the code is working as expected.

node server.js

Your console should display – Running on port 8001.

Close the server using ctrl+c

On hitting the URL – http:// localhost: 8001, you won’t see anything as we still need to work on our front-end. So far, we are a bit done with the socket listener in our sever.js file.

Now let’s move on to my favorite part of building the real time chat application, i.e., front-end.

Front-end part: React Component

We will be using create-react-app for it, some also prefer to configure Webpack, but that’s up to you. If you don’t have create-react-app installed on your system, use the below command-

npm i create-react-app

Now let’s create our React application –

create-react-app chat-app-client
cd chat-app-client

You can remove unwanted files like – favicon.ico and logo.svg from your file structure.

Now, as we know, Socket.IO uses Engines.IO, due to which we need to install Socket.IO at both client and server sides. So, it’s time to install socket.io-client

npm i socket.io-client

Client-Server Connection

This section will see how to connect the client with the server and enable communication in real time chat application using Socket.IO.

import React from 'react';
import socketClient from 'socket.io-client';
const SERVER = "http:// 127.0.0.1:8001";
function ChatApp() {
 let socket_io = socketClient(SERVER);
   return (
      < div >
        < p >Just checking if this is working!< /p >
      < /div >
    );
}
export default ChatApp;

Make these necessary changes in your server.js file so that the client listens to all the emitted events from the backend.

//server.js

let express = require('express')
let http = require('http')
let socketIO = require('socket.io') 

const PORT = 8001 
let app = express() 
let server = http.Server(app) 
let io = socketIO(server) 

const STATIC = [‘global_notif, global_chats’];

io.on(“connection”, (socket_io) => {
  console.log('User is connected successfully');
  socket_io.emit(“connection”, null);
  
  socket_io.on(“disconnect”, () => {
    console.log('Sorry! User is unfortunately disconnected');
  })
})

server.listen(PORT, () => {
   console.log(`Running on port ${port}.`);
});

Due to the function socket_io_emit, events can be emitted to the front end from the socket connection. Keep in mind that this transmission of data will be possible only with recently connected clients.

Now, the web socket connection is developed, so let’s proceed to build Chat.

How to Build Chat application?

We will have a folder named Chat, which will consist of our Channel’s components and the main Component of Chat. I won’t be adding CSS files for designing; instead, I’ll focus on the logic and components.

//Main_Chat.js

import React, { Component } from 'react';
import { Channels } from './Channels';

export class Main_Chat extends Component {
state = {
    all_channels: [
        { id: 10, name: 'John', members: 20}
      ]
    }
  render() {
     return (
        < div >
‍           < Channels all_channels={this.state.all_channels} / >
‍        < /div >
       );
    }
‍}

// Channels.js

import React, { Component } from 'react';

export class Channels extends Component {
   render() {
     let channel_list = `Sorry, No channels available`;
       if (this.props.all_channels) {
          list = this.props.all_channels.map(c =>  
          < p > {c.name} < /p >
       }
       return (
          < div >
             {channel_list}
‍          < /div >
        );
    }
‍}

So, we have two files here- Main_Chat.js and Channels.js. Main_Chat.js includes the Channels.js, which will display data related to the channel list using the prop all_channels. We are done with the Chat folder now, moving ahead to create a message folder for Message Panel. We will build two files in that folder, namely Main_Message.js and Messages.js.

//Main_Message.js

import React, { Component } from 'react';

export class Main_Message extends Component {
   render() {
      return (
          < div >
              < p >{this.props.senderName}< /p >
              < span >{this.props.text}< /span >
           < /div >
        )
    }
‍}

//Messages.js

import React, { Component } from 'react';
import { Main_Message } from './Main_Message';

export class Messages extends Component {
    render() {

        let msg_list = 
No messages!
; if (this.props.channel.messages) { const { msgs } = this.props list = msgs.channel.messages.map(msg => ) /> } return ( < > < p >{msg_list}< /p > ‍ < > < input type="text" > < button >Send< /button > ‍ < /> < /> ); } }

So far, we had set up the real time chat app with Express, ReactJS, and Socket.IO; now, without further ado, let’s move on to develop logic.

Logical part: Sending and Receiving Messages

We are done with the simple interface, and I hope you’ve managed your designing too. Moving on to focus on the logic part of our real time chat application, i.e., how to send and receive the messages?

How to fetch the channels?

Add the following code into your server.js file for retrieving the current channel’s data –

// server.js

app.get('/getAllChannels', (request, response) => {
   request.json({
       all_channels: STATIC
   })
‍});

This was for the backend side, write the following for frontend –

// Main_Chat.js

componentDidMount() {
   this.loadAllChannels();
‍}
loadAllChannels = async () => {         fetch('http:// localhost:8001/getAllChannels').then(async response => {
       let all_data = await response.json();
           this.setState({ all_channels: all_data.channels });
   })
‍}

Now, there’s a need for some events to be emitted and listeners in real time chat app. Whenever a channel is being selected, it should call an event that will eventually be handled in the backend. Also, the front-end has to look after the event. The front-end should have the same events emitted by the back-end to capture it and vice-versa.

// Main_Chat.js

handleSelect = (channel_id) => {
       this.socketIO.emit('channel-join', channel_id)
   }   
   render() {
    const { all_channels } = this.state;


return (
          < Channels all_channels={all_channels}   onChannelSelect={this.handleSelect} / >
       );
‍}

// server.js

io.on('connection', (socket_IO) => { 
    console.log('User is connected successfully!');
    socket_IO.emit('connection', null);
    socket_IO.on('channel_join', channel_id => {
        console.log('channel join', channel_id);
        STATIC.forEach(i => {
            if (i.id === channel_id) {
                if (i.sockets.indexOf(socket_IO.id) == (-1)) {
                    i.sockets.push(socket_IO.id);
                    i.members++;
                    io.emit('channel', c);
                }
            } else {
               let channel_index =              i.sockets.indexOf(socket_IO.id);
                if (channel_index != (-1)) {
                    i.sockets.splice(channel_index, 1);
                    i.members--;
                    io.emit('channel', c);
                }
            }
        });
 
        return channel_id;
    })
});

How to send messages?

Heading towards our last section of the blog – How to Build a Real-time Chat App with Express, ReactJS, and Socket.IO? After establishing a stable WebSocket connection, it’s time to learn how to send messages over it. This section will store the message typed in the textbox and then send that message by clicking Send. Open your Main_Chat.js file and make the necessary changes.

setUpSocketIO = () => {

 let socketIO = socketClient(SERVER);
 socketIO.on('connection', () => {
const { channels } = this.state;
   if (channels) {
     this.handleSelect(channels.id);
   }
 });

 socketIO.on('channel', channel => {
  
   let all_channels = this.state.all_channels;
    all_channels.forEach(i => {
       if (i.id === channel.id) {
         i.members = i.members;
       }
 });

 this.setState({ all_channels });});

socketIO.on('message', msg => {
 let all_channels = this.state.all_channels
   all_channels.forEach(i => {
     if (i.id === msg.channel_id) {
       if (!i.messages) {
         i.messages = [msg];
       } else {
         i.messages.push(msg);
       }
     }
   });
   this.setState({ all_channels });
 });

 this.socketIO = socketIO;
}
onSendingMessage = (id, msg) => {
 this.socketIO.emit('send-message', 
    { channel_id: id, 
     text: msg, 
     name: this.socketIO.id, 
     id: Date.now() 
    });
 }

render() {
const { all_channels } = this.state;
 return (
   < >
     < Channels all_channels={all_channels}      onChannelSelect={this.handleSelect} 
      / >    
     < Messages onSendMessage={this.onSendingMessage} channel={all_channel} / > 
   < />  
 );
‍}

So, this was for the front-end part. Implementation at the back-end is quite simpler than this; we just have to broadcast the messages.

socketIO.on('send-message', msg => {
   io.emit('message', msg);
‍})

This was all about how to build your own real time chat app with Express, ReactJS, and Socket.IO. I hope the purpose of landing on this blog has been satisfied. With the combination of ReactJs and Socket.IO, you can build brilliant real time chat applications.

Conclusion

Here at Bacancy Technology, we provide you the best guidance for various technologies, including ReactJs and NodeJs. You can find the best coding practices being followed by TDD and BDD here. If you are looking to hire full stack developer who can help you build a real-time chat app with Express, ReactJS, and Socket.IO, then you have landed on the right blog post. Get in touch with us to fulfill your custom business requirements.


Expand Your Digital Horizons With Us.

Start a new project or take an existing one to the next level. Get in touch to start small, scale-up, and go Agile.


Or
E-mail us : [email protected]

Your Success Is Guaranteed !

Related Articles

Golang vs Java
Ritwik Verma

March 14, 2023

Full Stack

Golang vs Java: The Right Choice for Your Web App Development in 2023

By : Ritwik Verma

Quick Summary: Business owners within the tech marketplace want to make sure to rank at the top in their business niche. We know choosing the...

12 Minute Read
Read More
ChatGPT Integration with Node and Vue
Ritwik Verma
Santosh Yadav

February 23, 2023

Full Stack

ChatGPT Integration with Node and Vue: The AI Chatbot Evolution

By : Ritwik Verma & Santosh Yadav

Quick Summary: As technology becomes increasingly integrated into our daily lives, it's important to consider how it will shape the future. One area that's particularly...

9 Minute Read
Read More
React Native vs Kotlin
Paridhi Wadhwani

February 2, 2023

Full Stack

React Native vs Kotlin: Which Best Serves Your App Requirements?

By : Paridhi Wadhwani

Highlights on React Native vs Kotlin: 🟠 Both React Native and Kotlin are open-source, but one is a framework and the other is a programming...

11 Minute Read
Read More
india India (HQ)

Corporate House
15-16, Times Corporate Park, Thaltej, Ahmedabad, Gujarat 380059

USA USA

601 Brickell Key Drive, Suite 700, Miami, Florida, 33131, USA

canada Canada

71 Dawes Road, Brampton, On L6X 5N9, Toronto

australia-flag Australia

351A Hampstead Rd, Northfield SA 5085

UAE UAE

1608 Clover Bay, Business Bay, Dubai, UAE. PO Box 62049

sweden Sweden

Junkergatan 4, 126 53 Hagersten


Great Place to Work
Get in Touch
call-yellow-icon

Contact Number

+1 347 441 4161

gmail-icon

Email Us

[email protected]


  • Bacancy Behance
  • Bacancy Uplabs
  • Bacancy Pinterest
  • Brochure
  • Quality Assurance
  • Resources
  • Tutorials
  • Customer Reviews
  • Privacy Policy
  • FAQs
  • Contact Us
  • Sitemap
  • Employee
bacancy google review 4.6
bacancy google review
bacancy glassdoor review 4.5
bacancy glassdoor review
bacancy clutch review 4.8
bacancy clutch review
bacancy goodfirms review 4.5
bacancy goodfirms review
X

Get Our Newsletter

Be The First To Get The Latest Updates And Tutorials.

Request A Free Consultation

Before You Go...

Try our free consultation to visualize the best outcome of your business ideas.

INSTANT 30 MIN FREE CONSULTATION CALL