Building a chat app with Socket.io and React 🚀
We have all encountered chat over the web, that can be Facebook, Instagram, Whatsapp and the list goes on. Just to give a bit of context, you send a message to a person or a group, they see the message and reply back. Simple yet complex. To develop…

In this article, we’ll leverage the real-time communication provided by Socket.io to create an open chat application that allows users to send and receive messages from several users on the application. You will also learn how to detect the users who are online and when a user is typing.
💡 To read this article you’ll need to have a basic knowledge of React.js and Node.js to comprehend this article.
What is Socket.io?
Socket.io is a popular JavaScript library that allows us to create real-time, bi-directional communication between web browsers and a Node.js server. It is a highly performant and reliable library optimized to process a large volume of data with minimal delay. It follows the WebSocket protocol and provides better functionalities, such as fallback to HTTP long-polling or automatic reconnection, which enables us to build efficient chat and real-time applications.
Novu – the first open-source notification architecture
Just a quick background about us. Novu is the first open-source notification infrastructure. We basically help to manage all the product notifications. It can be In-App (the bell icon like you have in Facebook – Websockets), Emails, SMSs, and so on.We are trending now on Github, and every additional star can help us to reach more developers. Happy if you can help me out ❤️ https://github.com/novuhq/novu
How to connect a React.js app to Node.js via Socket.io
In this section, we’ll set up the project environment for our chat application. You’ll also learn how to add Socket.io to a React and Node.js application and connect both development servers for real-time communication via Socket.io.
Create the project folder containing two sub-folders named client and server.
Navigate into the client folder via your terminal and create a new React.js project.
Install Socket.io client API and React Router. React Router is a JavaScript library that enables us to navigate between pages in a React application.
Delete the redundant files such as the logo and the test files from the React app, and update the App.js file to display Hello World as below.
Next, navigate into the server folder and create a package.json file.
Install Express.js, CORS, Nodemon, and Socket.io Server API.
Express.js is a fast, minimalist framework that provides several features for building web applications in Node.js. CORS is a Node.js package that allows communication between different domains.
Nodemon is a Node.js tool that automatically restarts the server after detecting file changes, and Socket.io allows us to configure a real-time connection on the server.
Create an index.js file – the entry point to the web server.
Set up a simple Node.js server using Express.js. The code snippet below returns a JSON object when you visit the http://localhost:4000/api in your browser.
Import the HTTP and the CORS library to allow data transfer between the client and the server domains.
Next, add Socket.io to the project to create a real-time connection. Before the app.get() block, copy the code below.
From the code snippet above, the socket.io("connection") function establishes a connection with the React app, then creates a unique ID for each socket and logs the ID to the console whenever a user visits the web page.
When you refresh or close the web page, the socket fires the disconnect event showing that a user has disconnected from the socket.
Next, configure Nodemon by adding the start command to the list of the scripts in the package.json file. The code snippet below starts the server using Nodemon.
You can now run the server with Nodemon by using the command below.
Open the App.js file in the client folder and connect the React app to the Socket.io server.
Start the React.js server.
Check the terminal where the server is running; the ID of the React.js client appears in the terminal.
Congratulations 🥂 , the React app has been successfully connected to the server via Socket.io.
💡 For the remaining part of this article, I will walk you through creating the web pages for the chat application and sending messages back and forth between the React app and the Node.js server. I’ll also guide you on how to add the auto-scroll feature when a new message arrives and how to fetch active users in your chat application.
Creating the Home page for the chat application
In this section, we’ll create the home page for the chat application that accepts the username and saves it to the local storage for identification.
Create a folder named components within the client/src folder. Then, create the Home page component.
Copy the code below into the Home.js file. The code snippet displays a form input that accepts the username and stores it in the local storage.
Next, configure React Router to enable navigation between the pages of the chat application. A home and chat page is enough for this application.
Copy the code below into the src/App.js file.
The code snippet assigns different routes for the Home and Chat page of the application using React Router v6 and passes the Socket.io library into the components. We’ll create the Chat page in the upcoming section.
Navigate into the src/index.css file and copy the code below. It contains all the CSS required for styling this project.
We’ve created the home page of our chat application. Next, let’s design the user interface for the chat page.
Creating the Chat page of the application
In this section, we’ll create the chat interface that allows us to send messages and view active users.
From the image above, the Chat page is divided into three sections, the Chat Bar – sidebar showing active users, the Chat Body containing the sent messages and the header, and the Chat Footer – the message box and the send button.
Since we’ve been able to define the layout for the chat page, you can now create the components for the design.
Create the ChatPage.js file and copy the code below into it. You will need to ChatBar, ChatBody, and ChatFooter components.
The Chat Bar component
Copy the code below into the ChatBar.js file.
The Chat Body component
Here, we’ll create the interface displaying the sent messages and the page headline.
The Chat Footer component
Here, we’ll create the input and the send button at the bottom of the chat page. The message and the username appear in the console after submitting the form.
Sending messages between the React app and the Socket.io server
In this section, you’ll learn how to send messages from the React app to the Node.js server and vice-versa via Socket.io. To send the messages to the server, we will need to pass the Socket.io library into the ChatFooter – component that sends the messages.
Update the ChatPage.js file to pass the Socket.io library into the ChatFooter component.
Update the handleSendMessage function in the ChatFooter component to send the message to the Node.js server.
The handleSendMessage function checks if the text field is empty and if the username exists in the local storage (sign-in from the Home page) before sending the message event containing the user input, username, the message ID generated, and the socket or client ID to the Node.js server.
Open the index.js file on the server, update the Socket.io code block to listen to the message event from the React app client, and log the message to the server’s terminal.
We’ve been able to retrieve the message on the server; hence, let’s send the message to all the connected clients.
Update the ChatPage.js file to listen to the message from the server and display it to all users.
From the code snippet above, Socket.io listens to the messages sent via the messageResponse event and spreads the data into the messages array. The array of messages is passed into the ChatBody component for display on the UI.
Update the ChatBody.js file to render the data from the array of messages.
The code snippet above displays the messages depending on whether you or another user sent the message. Messages in green are the ones you sent, and red is messages from other users.
Congratulations 🥂, the chat application is now functional. You can open multiple tabs and send messages from one to another.
How to fetch active users from Socket.io
In this section, you’ll learn how to get all the active users and display them on the Chat Bar of the chat application.
Open the src/Home.js and create an event that listens to users when they sign in. Update the handleSubmit function as below:
Create an event listener that updates an array of users on the Node.js server whenever a user joins or leaves the chat application.
socket.on("newUser") is triggered when a new user joins the chat application. The user’s details (socket ID and username) are saved into the users array and sent back to the React app in a new event named newUserResponse.In socket.io("disconnect"), the users array is updated when a user leaves the chat application, and the newUserReponse event is triggered to send the updated the list of users to the client.
Next, let’s update the user interface, ChatBar.js, to display the list of active users.
The useEffect hook listens to the response sent from the Node.js server and collects the list of active users. The list is mapped into the view and updated in real-time.
Congratulations 💃🏻, we’ve been able to fetch the list of active users from Socket.io. Next, let’s learn how to add some cool features to the chat application.
Optional: Auto-scroll and Notify users when a user is typing
In this section, you’ll learn how to add the auto-scroll feature when you receive a new message and the typing feature that indicates that a user is typing.
Auto-scroll feature
Update the ChatPage.js file as below:
Update the ChatBody component to contain an element for lastMessageRef.
From the code snippets above, lastMessageRef is attached to a div tag at the bottom of the messages, and its useEffect has a single dependency, which is the messages array. So, when the messages changes, the useEffect for the lastMessageRef re-renders.
Notify others when a user is typing
To notify users when a user is typing, we’ll use the JavaScript onKeyDown event listener on the input field, which triggers a function that sends a message to Socket.io as below:
From the code snippet above, the handleTyping function triggers the typing event whenever a user is typing into the text field. Then, we can listen to the typing event on the server and send a response containing the data to other users via another event called typingResponse.
Next, listen to the typingResponse event in the ChatPage.js file and pass the data into the ChatBody.js file for display.
Update the ChatBody.js file to show the typing status to the users.
Congratulations, you’ve just created a chat application!💃🏻
Feel free to improve the application by adding the Socket.io private messaging feature that allows users to create private chat rooms and direct messaging, using an authentication library for user authorization and authentication and a real-time database for storage.
Conclusion
Socket.io is a great tool with excellent features that enables us to build efficient real-time applications like sports betting websites, auction and forex trading applications, and of course, chat applications by creating lasting connections between web browsers and a Node.js server.
If you’re looking forward to building a chat application in Node.js, Socket.io may be an excellent choice.
You can find the source code for this tutorial here: https://github.com/novuhq/blog/tree/main/open-chat-app-with-socketIO
Next article
In the next part of the series I am going to talk about connecting the chat-app into browser notifications (web-push), so you can inform users about new messages if they are offline.
Help me out!
If you feel like this article helped you understand WebSockets better! I would be super happy if you could give us a star! And let me also know in the comments ❤️ https://github.com/novuhq/novu
Thank you for reading!