How to Build a Real-Time Group Chat App with Socket.io
Socket.io makes real-time, bidirectional communication between clients and servers effortless. In this tutorial, we will build a simple group chat application where multiple users can exchange messages instantly. The entire project uses Node.js, Express, and Socket.io — no complex frontend frameworks required.
Let’s start by setting up the project. Create a new directory, initialize it with npm init -y, and install the required dependencies: npm install express socket.io. This gives us a lightweight web server and the real-time engine for WebSocket fallback support.
Setting Up the Server
Create an index.js file. This server will serve static files and handle Socket.io connections. Here is the core setup:
- Import
expressandhttp, create an HTTP server. - Initialize Socket.io on that server.
- Listen on a port (e.g., 3000).
When a client connects, we need to listen for incoming 'chat message' events. On receiving one, broadcast it to all connected clients using io.emit().
Handling Client-Server Events
In the server-side connection event, add listeners:
socket.on('chat message', (msg) => { io.emit('chat message', msg); })- This sends every message from any user to every connected client.
Storing messages in memory or a database is optional — for this tutorial we focus on real-time relay only.
Building the Client Interface
Create a public folder with an index.html file. Include the Socket.io client library from your server (/socket.io/socket.io.js). Then:
- Add a message form with an input field and send button.
- Add a
<ul>to display incoming messages. - Connect to the socket:
var socket = io(); - On form submit, emit
'chat message'with the input value. - Listen for
'chat message'events and append messages to the list.
Running the App
Start your server with node index.js and open http://localhost:3000 in multiple browser tabs. Any message sent from one tab appears instantly in all others. Congratulations — you’ve built a functional group chat!
From here, you can add usernames, message persistence, typing indicators, or room support. Socket.io’s flexibility makes scaling these features straightforward.