Paramclasses Academy - Blog

Tutorials Details

←
Post 32 of 40
→

Real-Time Applications with Node.js and Socket.IO: Build a Live Chat Application

Real-Time Applications with Node.js and Socket.IO: Build a Live Chat Application

October 30, 2026

✦ Real-Time Applications with Node.js and Socket.IO: Build a Live Chat Application

Modern web applications often need to exchange information instantly. For example, messaging applications, live notifications, online gaming platforms, and customer support systems must update information without refreshing the webpage.

Traditional HTTP requests usually follow a request-and-response pattern. However, some applications need continuous communication between the browser and server.

This is where WebSockets and Socket.IO become useful.

In this practical tutorial, you will learn how to build a real-time chat application using Node.js, Express.js, and Socket.IO. You will create a server, connect multiple browser clients, send messages instantly, and display messages without refreshing the page.

✦ What Is a Real-Time Application?

A real-time application allows users to exchange or receive information immediately when an event occurs.

For example:

  • WhatsApp-style messaging applications.

  • Live customer support chat.

  • Real-time notifications.

  • Online multiplayer games.

  • Live order tracking.

  • Collaborative editing applications.

  • Live dashboards.

When one user sends a message, the server can distribute that message to connected users immediately.

✦ What Is Socket.IO in Node.js?

Socket.IO is a JavaScript library that enables real-time, bidirectional communication between a client and a server.

It provides features such as:

  • Real-time event-based communication.

  • Automatic reconnection.

  • Broadcasting messages.

  • Rooms and namespaces.

  • Connection and disconnection events.

  • Support for WebSocket and fallback transports.

Socket.IO is not exactly the same as the native WebSocket protocol. It provides its own communication protocol and additional features.

✦ How Socket.IO Works

A basic Socket.IO communication process looks like this:

  1. A user opens the chat webpage.

  2. The browser connects to the Node.js server using Socket.IO.

  3. The server accepts the connection.

  4. The user enters a message.

  5. The browser sends a message event to the server.

  6. The server receives the event.

  7. The server broadcasts the message to connected users.

  8. Other users receive the message instantly.

Unlike repeatedly refreshing a webpage, Socket.IO keeps a communication connection available while the client is connected.

✦ Step 1: Create a Node.js Project

Create a project folder:

mkdir nodejs-chat-app
cd nodejs-chat-app
npm init -y

Install Express and Socket.IO:

npm install express socket.io

Our project structure will look like this:

nodejs-chat-app/
│
├── public/
│   ├── index.html
│   ├── style.css
│   └── script.js
│
├── server.js
└── package.json

The public folder will contain our frontend files.

✦ Step 2: Create the Node.js Socket.IO Server

Create a file named server.js:

const express = require("express");
const http = require("http");
const { Server } = require("socket.io");

const app = express();

const server = http.createServer(app);

// Create Socket.IO server
const io = new Server(server);

// Serve frontend files
app.use(express.static("public"));

// Handle client connections
io.on("connection", (socket) => {

    console.log("User connected:", socket.id);

    // Receive chat message
    socket.on("chatMessage", (data) => {

        const messageData = {
            username: String(data.username).trim().slice(0, 30),
            message: String(data.message).trim().slice(0, 1000),
            time: new Date().toLocaleTimeString()
        };

        if (!messageData.username || !messageData.message) {
            return;
        }

        // Send message to all connected users
        io.emit("chatMessage", messageData);

    });

    // Handle user disconnection
    socket.on("disconnect", () => {

        console.log("User disconnected:", socket.id);

    });

});

// Start server
const PORT = 3000;

server.listen(PORT, () => {

    console.log(`Server running at http://localhost:${PORT}`);

});

Understanding the code:

  • http.createServer(app) creates an HTTP server using Express.

  • new Server(server) attaches Socket.IO to that server.

  • io.on("connection") runs when a client connects.

  • socket.on("chatMessage") listens for incoming chat messages.

  • io.emit("chatMessage") broadcasts the message to all connected clients.

  • disconnect detects when a client disconnects.

For a learning project, the example accepts a username from the browser. In a production chat application, authenticate users and obtain their identity from a trusted server-side session or verified token instead of trusting a client-provided username.

✦ Step 3: Create the HTML Chat Interface

Inside the public folder, create index.html:

<!DOCTYPE html>
<html>
<head>

    <title>Node.js Real-Time Chat</title>

    <link rel="stylesheet" href="style.css">

</head>

<body>

    <div class="chat-container">

        <h2>Real-Time Chat Application</h2>

        <div id="messages" class="messages"></div>

        <form id="chatForm">

            <input
                type="text"
                id="username"
                placeholder="Enter your name"
                maxlength="30"
                required
            >

            <input
                type="text"
                id="message"
                placeholder="Type your message..."
                maxlength="1000"
                required
            >

            <button type="submit">
                Send
            </button>

        </form>

    </div>

    <script src="/socket.io/socket.io.js"></script>

    <script src="script.js"></script>

</body>
</html>

The HTML page contains:

  • Username input.

  • Message input.

  • Send button.

  • Message display area.

The Socket.IO client library is automatically served by the Socket.IO server at /socket.io/socket.io.js.

✦ Step 4: Design the Chat Application Using CSS

Create public/style.css:

* {
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    background: #eef2f7;
    margin: 0;
    padding: 30px;
}

.chat-container {
    max-width: 650px;
    margin: auto;
    background: white;
    padding: 25px;
    border-radius: 10px;
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

h2 {
    text-align: center;
    color: #1e293b;
}

.messages {
    height: 350px;
    overflow-y: auto;
    border: 1px solid #ddd;
    padding: 15px;
    margin-bottom: 15px;
    background: #f8fafc;
}

.message {
    padding: 10px;
    margin-bottom: 10px;
    background: #dbeafe;
    border-radius: 6px;
    overflow-wrap: anywhere;
}

.message strong {
    color: #1d4ed8;
}

.message small {
    display: block;
    color: #64748b;
    margin-top: 5px;
}

form {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

input {
    padding: 12px;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button {
    padding: 12px;
    background: #2563eb;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
}

button:hover {
    background: #1d4ed8;
}

This CSS creates a simple chat interface with a message area, input fields, and a send button.

✦ Step 5: Connect the Frontend with Socket.IO

Create public/script.js:

// Connect to Socket.IO server
const socket = io();

// Get HTML elements
const chatForm = document.getElementById("chatForm");

const usernameInput = document.getElementById("username");

const messageInput = document.getElementById("message");

const messages = document.getElementById("messages");

// Send message
chatForm.addEventListener("submit", function (e) {

    e.preventDefault();

    const username = usernameInput.value.trim();

    const message = messageInput.value.trim();

    if (!username || !message) {
        return;
    }

    // Send event to server
    socket.emit("chatMessage", {
        username: username,
        message: message
    });

    // Clear message input
    messageInput.value = "";

    messageInput.focus();

});

// Receive message from server
socket.on("chatMessage", function (data) {

    const messageDiv = document.createElement("div");

    messageDiv.className = "message";

    const username = document.createElement("strong");
    username.textContent = data.username;

    const messageText = document.createElement("div");
    messageText.textContent = data.message;

    const time = document.createElement("small");
    time.textContent = data.time;

    messageDiv.appendChild(username);
    messageDiv.appendChild(messageText);
    messageDiv.appendChild(time);

    messages.appendChild(messageDiv);

    // Scroll to latest message
    messages.scrollTop = messages.scrollHeight;

});

Understanding the code:

  • io() connects the browser to the Socket.IO server.

  • socket.emit() sends an event to the server.

  • socket.on() listens for events from the server.

  • createElement() creates message elements safely.

  • textContent displays message text without interpreting it as HTML.

Using textContent instead of inserting user messages with innerHTML helps prevent HTML injection and cross-site scripting issues.

✦ Step 6: Run Your Real-Time Chat Application

Open your terminal and run:

node server.js

You should see:

Server running at http://localhost:3000

Open your browser:

http://localhost:3000

Enter a username and send a message.

Now open the same URL in another browser window or an incognito window.

Enter another username and send a message.

You will see messages appearing in both browser windows without refreshing the page.

<text> </text>

✦ Step 7: Understand Important Socket.IO Events

Socket.IO uses events to exchange information.

Here are some commonly used methods:

Method Purpose
io.on("connection") Detect a new connection
socket.emit() Send an event to the server or client
socket.on() Listen for an event
io.emit() Send an event to all connected clients
socket.broadcast.emit() Send to everyone except the sender
socket.disconnect() Disconnect a socket

For example, if you do not want the sender to receive their own message through the broadcast, replace:

io.emit("chatMessage", messageData);

with:

socket.broadcast.emit("chatMessage", messageData);

Remember that io.emit() includes the sender, while socket.broadcast.emit() excludes the sending socket.

✦ Step 8: Add a User Connection Notification

You can also display a message when someone connects.

Inside the connection callback in server.js, add:

io.emit("userNotification", {
    message: "A new user has joined the chat"
});

In script.js, listen for that event:

socket.on("userNotification", function (data) {

    console.log(data.message);

});

You can later display this notification in the chat interface.

✦ Real-Time Chat Application vs Traditional HTTP

Traditional HTTP Socket.IO
Request-response communication Event-based communication
Usually separate requests Persistent connection while connected
Often requires polling for updates Supports real-time event delivery
Suitable for regular APIs Suitable for live communication

Both approaches are useful. A typical application may use REST APIs for user registration and data management, and Socket.IO for real-time messaging.

✦ Important Socket.IO Security Best Practices

When building a real-world application, follow these practices:

  1. Authenticate users before allowing them to join private chats.

  2. Validate incoming messages on the server.

  3. Limit message length and event frequency.

  4. Use HTTPS and secure WebSocket connections in production.

  5. Do not trust usernames or user IDs sent by clients.

  6. Use rooms to separate private conversations.

  7. Restrict which origins can connect to your Socket.IO server.

  8. Avoid sending private messages through global broadcasts.

  9. Store chat history in a database if messages must persist.

  10. Implement rate limiting and abuse protection.

The example in this tutorial is a learning project. Messages are sent only to connected clients and are not saved permanently.

✦ Frequently Asked Questions

Q1. What is Socket.IO in Node.js?

Socket.IO is a JavaScript library that enables real-time, bidirectional, event-based communication between clients and servers.

Q2. Can we build a live chat application using Node.js?

Yes. Node.js with Socket.IO can be used to create real-time chat applications, messaging systems, and customer support tools.

Q3. What is the difference between WebSocket and Socket.IO?

WebSocket is a communication protocol. Socket.IO is a library that provides event-based communication and additional features such as automatic reconnection and rooms.

Q4. Does Socket.IO require a database?

No. You can exchange messages without a database. However, you need a database if you want to store chat history permanently.

Q5. Can Socket.IO support multiple users?

Yes. Socket.IO supports multiple connected clients and provides broadcasting and room features for communication between users.

✦ Conclusion

Real-time communication is an important part of modern web development. With Node.js and Socket.IO, developers can build live chat systems, notification services, messaging platforms, and other interactive applications.

In this tutorial, we created a real-time chat application using Express.js and Socket.IO. We connected multiple browser clients, sent messages through events, and displayed incoming messages without refreshing the page.

Practice this project and then try adding user authentication, private chat rooms, MySQL chat history, and online user status.

Learn practical Node.js, Express.js, MySQL, REST API Development, and Backend Programming with Param Classes.

←
Post 32 of 40
→