Backend

Building Chat Applications with Socket.io

Mayur Dabhi
Mayur Dabhi
May 3, 2026
15 min read

The first version of most chat features is a setInterval that hits /messages every couple of seconds. It works on your laptop. Then you have a few hundred people with the page open, the server spends most of its time answering "nothing new", and messages still show up a second or two late. That's usually when people reach for WebSockets, and in the Node.js world that usually means Socket.io.

This post builds a small but complete chat app with Express and Socket.io: rooms, private messages, typing indicators, online presence, and what changes when you run more than one server.

Why Socket.io and not raw WebSockets?

You get things you'd otherwise write yourself: fallback to HTTP long-polling when a proxy blocks WebSockets, automatic reconnection, rooms, namespaces, and acknowledgements. The catch is that Socket.io has its own protocol on top of WebSocket, so a plain new WebSocket() client can't talk to a Socket.io server. Both ends need the Socket.io library.

How Socket.io Works

With plain HTTP, the client has to start every exchange. The server can't tell a browser "you have a new message" unless the browser asks first. So for chat you either poll constantly, which wastes requests, or poll slowly and accept that messages arrive late.

Socket.io opens a persistent, two-way connection, using WebSockets when it can and long-polling when it can't. After the handshake, either side can send an event whenever it wants:

HTTP Polling Client Server GET /messages? 200 (empty) GET /messages? 200 (empty) GET /messages? 200 (1 new msg!) Wasted requests until msg arrives Socket.io (WebSocket) Client Server Handshake (once) Persistent connection open Server pushes message! Client sends message Server broadcasts to room Pushed as soon as it happens

HTTP Polling vs Socket.io persistent connection

FeatureHTTP PollingSocket.io
Connection overheadPer-requestOne-time handshake
Server pushNot supportedNative
LatencyUp to one polling intervalRoughly one network round trip
Bandwidth usageHigh (headers repeated)Low (minimal framing)
Fallback supportN/AAuto (long-polling)
ReconnectionManualAutomatic

Setting Up the Project

The server is Node.js with Express and Socket.io. The frontend is plain JavaScript. You don't need React or Vue for this; the Socket.io client does the real-time work and the rest is DOM updates.

1

Initialize the project

Create a new directory and initialize a Node.js package, then install the required dependencies.

Terminal
mkdir chat-app && cd chat-app
npm init -y

# Core dependencies
npm install express socket.io

# Optional but useful
npm install dotenv cors

# Dev dependency
npm install --save-dev nodemon
2

Project structure

Keep the project organized with separate files for server logic, socket handlers, and the public frontend.

Project layout
chat-app/
├── server.js          # Express + Socket.io server
├── handlers/
│   └── chatHandler.js # Socket event handlers
├── public/
│   ├── index.html     # Chat UI
│   ├── style.css      # Styles
│   └── client.js      # Socket.io client logic
├── .env
└── package.json
3

Add start scripts

Add start and dev scripts to package.json.

package.json (scripts section)
"scripts": {
  "start": "node server.js",
  "dev": "nodemon server.js"
}

Building the Chat Server

The server keeps track of connected sockets, decides who gets each event, and manages room membership. Socket.io attaches to the same Node.js http server as Express, so everything runs on one port.

server.js
require('dotenv').config();
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const path = require('path');

const app = express();
const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: process.env.CLIENT_URL || '*',
    methods: ['GET', 'POST'],
  },
  // Ping every 25s, disconnect after 60s of no pong
  pingTimeout: 60000,
  pingInterval: 25000,
});

// Serve frontend
app.use(express.static(path.join(__dirname, 'public')));

// In-memory store: socketId → { username, room }
const users = {};

io.on('connection', (socket) => {
  console.log(`Socket connected: ${socket.id}`);

  // 1. User joins a room
  socket.on('join_room', ({ username, room }) => {
    // Leave any previous room
    const prev = users[socket.id];
    if (prev) {
      socket.leave(prev.room);
      io.to(prev.room).emit('user_left', {
        username: prev.username,
        time: new Date().toISOString(),
      });
    }

    // Register and join
    users[socket.id] = { username, room };
    socket.join(room);

    // Tell the joiner their history (omitted here, add a DB lookup)
    socket.emit('room_joined', { room, username });

    // Notify others in the room
    socket.to(room).emit('user_joined', {
      username,
      time: new Date().toISOString(),
    });

    // Broadcast updated user list for this room
    broadcastRoomUsers(room);
  });

  // 2. New chat message
  socket.on('send_message', ({ message, room }) => {
    const user = users[socket.id];
    if (!user) return;

    const payload = {
      id: `${Date.now()}-${socket.id}`,
      username: user.username,
      message,
      time: new Date().toISOString(),
    };

    // Emit to everyone in the room (including sender)
    io.to(room).emit('receive_message', payload);
  });

  // 3. Typing indicator
  socket.on('typing', ({ room, isTyping }) => {
    const user = users[socket.id];
    if (!user) return;
    socket.to(room).emit('user_typing', {
      username: user.username,
      isTyping,
    });
  });

  // 4. Private message
  socket.on('private_message', ({ toSocketId, message }) => {
    const sender = users[socket.id];
    if (!sender) return;

    const payload = {
      from: sender.username,
      fromId: socket.id,
      message,
      time: new Date().toISOString(),
    };

    // Send to recipient
    io.to(toSocketId).emit('private_message', payload);
    // Echo back to sender
    socket.emit('private_message', { ...payload, isSelf: true });
  });

  // 5. Cleanup on disconnect
  socket.on('disconnect', () => {
    const user = users[socket.id];
    if (user) {
      socket.to(user.room).emit('user_left', {
        username: user.username,
        time: new Date().toISOString(),
      });
      delete users[socket.id];
      broadcastRoomUsers(user.room);
    }
    console.log(`Socket disconnected: ${socket.id}`);
  });
});

function broadcastRoomUsers(room) {
  const roomUsers = Object.values(users)
    .filter(u => u.room === room)
    .map(u => u.username);
  io.to(room).emit('room_users', roomUsers);
}

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Chat server running on http://localhost:${PORT}`);
});
In-memory vs persistent storage

The users object lives in memory, so a restart wipes it. In production, put messages in a database (MongoDB, PostgreSQL) and session state in Redis, so history survives restarts and works across multiple nodes.

Creating the Chat Frontend

The Socket.io server serves its own browser bundle at /socket.io/socket.io.js, so there's no CDN or bundler involved. The client does two things: listens for server events and updates the DOM, and emits events when the user does something.

public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Socket Chat</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <!-- Join Screen -->
  <div id="join-screen">
    <h2>Join Chat</h2>
    <input id="username" placeholder="Your name" maxlength="20">
    <input id="room" placeholder="Room name (e.g. general)" value="general">
    <button id="join-btn">Join Room</button>
  </div>

  <!-- Chat Screen -->
  <div id="chat-screen" class="hidden">
    <aside id="sidebar">
      <h3>Online - <span id="room-name"></span></h3>
      <ul id="user-list"></ul>
    </aside>
    <main>
      <div id="messages"></div>
      <div id="typing-indicator"></div>
      <form id="message-form">
        <input id="message-input" placeholder="Type a message…" autocomplete="off">
        <button type="submit">Send</button>
      </form>
    </main>
  </div>

  <!-- Socket.io client (auto-served by the server) -->
  <script src="/socket.io/socket.io.js"></script>
  <script src="client.js"></script>
</body>
</html>
public/client.js
const socket = io();

let currentUser = '';
let currentRoom = '';
let typingTimer;

// ── Join ──────────────────────────────────────────
document.getElementById('join-btn').addEventListener('click', () => {
  const username = document.getElementById('username').value.trim();
  const room = document.getElementById('room').value.trim() || 'general';

  if (!username) return alert('Please enter a username');

  currentUser = username;
  currentRoom = room;

  socket.emit('join_room', { username, room });
});

socket.on('room_joined', ({ room }) => {
  document.getElementById('join-screen').classList.add('hidden');
  document.getElementById('chat-screen').classList.remove('hidden');
  document.getElementById('room-name').textContent = room;
});

// ── Messages ──────────────────────────────────────
document.getElementById('message-form').addEventListener('submit', (e) => {
  e.preventDefault();
  const input = document.getElementById('message-input');
  const message = input.value.trim();
  if (!message) return;

  socket.emit('send_message', { message, room: currentRoom });
  socket.emit('typing', { room: currentRoom, isTyping: false });
  input.value = '';
});

socket.on('receive_message', ({ username, message, time }) => {
  const isSelf = username === currentUser;
  appendMessage({ username, message, time, isSelf });
});

function appendMessage({ username, message, time, isSelf, isSystem }) {
  const div = document.createElement('div');
  div.className = isSystem
    ? 'msg-system'
    : isSelf ? 'msg msg-self' : 'msg msg-other';

  if (!isSystem) {
    div.innerHTML = `
      <span class="msg-user">${username}</span>
      <span class="msg-text">${escapeHtml(message)}</span>
      <span class="msg-time">${formatTime(time)}</span>
    `;
  } else {
    div.textContent = message;
  }

  const container = document.getElementById('messages');
  container.appendChild(div);
  container.scrollTop = container.scrollHeight;
}

// ── System events ─────────────────────────────────
socket.on('user_joined', ({ username }) => {
  appendMessage({ message: `${username} joined the room`, isSystem: true });
});

socket.on('user_left', ({ username }) => {
  appendMessage({ message: `${username} left the room`, isSystem: true });
});

// ── User list ─────────────────────────────────────
socket.on('room_users', (users) => {
  const ul = document.getElementById('user-list');
  ul.innerHTML = users
    .map(u => `<li class="${u === currentUser ? 'you' : ''}">${u}</li>`)
    .join('');
});

// ── Typing indicator ──────────────────────────────
document.getElementById('message-input').addEventListener('input', () => {
  socket.emit('typing', { room: currentRoom, isTyping: true });
  clearTimeout(typingTimer);
  typingTimer = setTimeout(() => {
    socket.emit('typing', { room: currentRoom, isTyping: false });
  }, 1500);
});

const activeTypers = new Set();

socket.on('user_typing', ({ username, isTyping }) => {
  if (isTyping) activeTypers.add(username);
  else activeTypers.delete(username);

  const el = document.getElementById('typing-indicator');
  if (activeTypers.size === 0) {
    el.textContent = '';
  } else if (activeTypers.size === 1) {
    el.textContent = `${[...activeTypers][0]} is typing…`;
  } else {
    el.textContent = `${activeTypers.size} people are typing…`;
  }
});

// ── Helpers ───────────────────────────────────────
function escapeHtml(str) {
  return str.replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"');
}

function formatTime(iso) {
  return new Date(iso).toLocaleTimeString([], { hour:'2-digit', minute:'2-digit' });
}
Always sanitize output

Never put raw user input into innerHTML. The escapeHtml helper escapes the message text, but look closely: ${username} in appendMessage and ${u} in the user list are still inserted unescaped, so a username like <img src=x onerror=alert(1)> would run script for everyone in the room. Escape those too, or use textContent. If you need rich formatting, use an allowlist sanitizer such as DOMPurify.

Chat Rooms and Namespaces

Socket.io gives you two ways to split up traffic: rooms and namespaces. People mix them up a lot. Most chat apps need plenty of rooms and maybe one or two namespaces.

Rooms are lightweight, server-side groupings within a single namespace. A socket can be in many rooms at once. Use them for chat channels, DM threads, or game lobbies.

// Server: join a room
socket.join('room:general');
socket.join('room:engineering');

// Leave a room
socket.leave('room:general');

// Emit to everyone IN the room (including sender)
io.to('room:general').emit('message', data);

// Emit to everyone EXCEPT the sender
socket.to('room:general').emit('message', data);

// Check which rooms a socket is in
console.log(socket.rooms); // Set { socketId, 'room:general', 'room:engineering' }

// Get all sockets in a room
const sockets = await io.in('room:general').fetchSockets();
console.log(sockets.length); // count of members

A namespace is a separate channel with its own event handlers and middleware, a bit like running several Socket.io instances on one server. Use them to keep different features apart (chat, notifications, admin).

// Server: separate namespaces
const chatNsp = io.of('/chat');
const adminNsp = io.of('/admin');

chatNsp.on('connection', (socket) => {
  console.log('chat user connected');
  socket.on('send_message', handler);
});

adminNsp.use((socket, next) => {
  // Middleware only for /admin namespace
  if (socket.handshake.auth.token === process.env.ADMIN_TOKEN) {
    next();
  } else {
    next(new Error('Unauthorized'));
  }
});

adminNsp.on('connection', (socket) => {
  // Admin-only events
  socket.on('kick_user', ({ socketId }) => {
    io.sockets.sockets.get(socketId)?.disconnect();
  });
});

// Client: connect to a specific namespace
const chatSocket = io('/chat');
const adminSocket = io('/admin', {
  auth: { token: 'secret-admin-token' }
});

Most "why did I get my own message twice" bugs come from picking the wrong target. Here are the ones you'll use:

// To a specific socket
io.to(socketId).emit('event', data);

// To everyone in a room
io.to('room-name').emit('event', data);

// To everyone in a room EXCEPT the sender
socket.to('room-name').emit('event', data);

// To everyone connected (all namespaces)
io.emit('event', data);

// To everyone EXCEPT the current socket
socket.broadcast.emit('event', data);

// To multiple rooms at once
io.to('room1').to('room2').emit('event', data);

// Volatile: skip if client is not connected
io.volatile.emit('typing', data); // OK to lose

// With acknowledgment (request/response over socket)
socket.emit('save_message', payload, (ack) => {
  console.log('Server confirmed:', ack.status);
});

Private Messaging

Every connection gets a unique socket.id, and every socket automatically joins a room with that ID, so you can send to one user directly. The tricky part is mapping a username to their current socket ID. A reconnect gives the user a new ID, so the map has to be updated every time.

server.js: username-to-socket mapping
// Map username → socketId for DMs
const usernameToSocket = new Map();

io.on('connection', (socket) => {

  socket.on('register', (username) => {
    usernameToSocket.set(username, socket.id);
    socket.data.username = username;
  });

  socket.on('private_message', ({ toUsername, message }) => {
    const recipientId = usernameToSocket.get(toUsername);

    if (!recipientId) {
      socket.emit('error', { msg: `${toUsername} is offline` });
      return;
    }

    const payload = {
      from: socket.data.username,
      message,
      time: new Date().toISOString(),
    };

    // Deliver to recipient
    io.to(recipientId).emit('private_message', payload);
    // Echo to sender (so their UI updates too)
    socket.emit('private_message', { ...payload, isSelf: true });
  });

  socket.on('disconnect', () => {
    const username = socket.data.username;
    if (username) usernameToSocket.delete(username);
  });
});

Message Delivery Receipts

Socket.io acknowledgements work well for delivery receipts. Pass a callback as the last argument to emit, and the server calls it once it has handled the event:

Acknowledgement pattern
// Client sends message with ack callback
socket.emit('send_message', { message, room }, (ack) => {
  if (ack.status === 'delivered') {
    markMessageDelivered(ack.messageId);
  }
});

// Server handles and responds via ack
socket.on('send_message', ({ message, room }, callback) => {
  const msgId = saveMessage(message); // your DB call
  io.to(room).emit('receive_message', { message, id: msgId });

  // Invoke the callback; this fires the client's ack handler
  callback({ status: 'delivered', messageId: msgId });
});

Online Presence and Typing Indicators

Seeing who's online and who's typing makes a chat app feel like a chat app. Neither is hard, but each has one trap that's easy to fall into.

Online presence

Keep the list on the server and broadcast it on connect and disconnect. Rely on socket.on('disconnect'), not a custom "logout" event. People close tabs, lose Wi-Fi, and put laptops to sleep, and none of that sends your logout event.

server.js: presence tracking
// Broadcast full online list whenever membership changes
function broadcastPresence() {
  const online = [...io.sockets.sockets.values()]
    .filter(s => s.data.username)
    .map(s => ({ username: s.data.username, id: s.id }));

  io.emit('presence_update', online);
}

io.on('connection', (socket) => {
  socket.on('register', (username) => {
    socket.data.username = username;
    broadcastPresence();
  });

  socket.on('disconnect', () => {
    broadcastPresence();
  });
});

Typing indicators done right

The naive version emits a typing event on every keypress, which means a fast typist sends several events a second to everyone in the room. Debounce it on the client instead: send "started typing" once, then "stopped typing" after 1.5 seconds without input. The server just relays these to the rest of the room:

Debounced typing: client.js
let typingTimer = null;
let isCurrentlyTyping = false;

input.addEventListener('input', () => {
  if (!isCurrentlyTyping) {
    isCurrentlyTyping = true;
    socket.emit('typing', { room, isTyping: true });
  }

  clearTimeout(typingTimer);
  typingTimer = setTimeout(() => {
    isCurrentlyTyping = false;
    socket.emit('typing', { room, isTyping: false });
  }, 1500);
});

// Also stop typing on send
form.addEventListener('submit', () => {
  clearTimeout(typingTimer);
  isCurrentlyTyping = false;
  socket.emit('typing', { room, isTyping: false });
});
FeatureImplementationKey consideration
Typing indicatorDebounced emitStop on send + timeout
Online presenceServer-side map + broadcastTrust disconnect, not logout event
Read receiptsAcknowledgement callbacksOnly reliable for connected sockets
Message historyDB query on room_joinedPaginate; don't load thousands at once
Unread badgeClient-side counter reset on focusUse Page Visibility API

Deployment and Scaling

The deployment issue that catches people out is sticky sessions. With several server instances behind a load balancer, every HTTP request from one client has to land on the same instance, because that instance holds the session. Long-polling and the initial handshake are separate HTTP requests, and if they get spread across instances the connection fails.

You'll recognise it in the browser console: the connection keeps dropping and reconnecting, and the server responds with 400 Bad Request and {"code":1,"message":"Session ID unknown"}. That's almost always a missing sticky session. Setting transports: ['websocket'] on the client also avoids it, but then you lose the long-polling fallback.

Client A Client B Load Balancer Server 1 Server 2 Server 3 Redis Pub/Sub adapter Redis adapter syncs events across all server instances

Multi-server Socket.io architecture with Redis adapter

Single-server pitfall

Run multiple Node.js processes without the Redis adapter and a message from a client on Server 1 never reaches clients on Server 2 or 3. Nothing errors. Users just see a half-empty room. Set up the adapter before you scale out (PM2 cluster mode counts too).

Terminal: install the Redis adapter
npm install @socket.io/redis-adapter ioredis
server.js: adapter configuration
const { createAdapter } = require('@socket.io/redis-adapter');
const { createClient } = require('ioredis');

const pubClient = createClient({ host: process.env.REDIS_HOST, port: 6379 });
const subClient = pubClient.duplicate();

Promise.all([pubClient.connect(), subClient.connect()]).then(() => {
  io.adapter(createAdapter(pubClient, subClient));
  server.listen(PORT);
  console.log(`Server on port ${PORT}`);
});

Production deployment checklist

Before you go live

  • CORS: Set origin to your specific domain, not '*'
  • Rate limiting: Throttle send_message events per socket to prevent spam (e.g., max 5 per second)
  • Input validation: Validate message length, sanitize all user content server-side
  • Authentication: Verify JWT or session cookie in the io.use() middleware before the connection is accepted
  • Redis adapter: Required for more than one process/pod
  • Sticky sessions: Configure your load balancer (Nginx, AWS ALB) for IP hash or cookie-based affinity
  • Connection limits: Monitor open socket count. A single Node.js process can hold tens of thousands of mostly idle connections, but the real limit depends on message volume and memory, so load test your own app. Raise the OS file descriptor limit (ulimit -n) too, since the default of 1024 on many Linux systems runs out fast
  • Graceful shutdown: Close all sockets before process exit to trigger proper client reconnection

When I'd use Socket.io (and when I wouldn't)

I'd use it when the server and client are both JavaScript, you need two-way traffic (chat, collaborative editing, multiplayer lobbies), and you want rooms, reconnection, and acknowledgements without building them yourself. For a Node.js team that's most real-time features.

Where it's the wrong tool

  • One-way updates only. Notifications, live scores, or a progress bar are often simpler with Server-Sent Events. SSE is plain HTTP, reconnects on its own, and doesn't need sticky sessions for the stream.
  • Non-JS clients. Native mobile apps or IoT devices need a Socket.io client library for their platform. If one isn't well maintained, plain WebSockets are easier to support.
  • Serverless hosting. Lambda and similar platforms don't keep long-lived connections. You'd need a managed service (API Gateway WebSockets, Pusher, Ably) instead.
  • Guaranteed delivery. Socket.io doesn't store messages for offline users. If a message must never be lost, write it to a database first and treat the socket as a notification that something new exists.
  • Laravel backends. If the app is already Laravel, broadcasting through Reverb or Pusher with Laravel Echo usually fits better than running a separate Node.js server.

If you're extending the app from here, add persistence and auth before anything else. File sharing, push notifications for offline users, or a React frontend all slot in as new events on the same connection, but none of them matter if history disappears on every restart or anyone can join a room by typing its name.

Socket.io Real-time Chat Node.js WebSockets Backend
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.