agyanadda@gmail.com

Node.js Real-time Apps with Socket.IO

Advanced Node.js 1 min read Updated Dec 3, 2026 Topic 26 of 30

Normal HTTP is request → response: the server cannot send data unless the client asks. WebSockets keep a connection open, so the server can push data instantly — for chat, live scores, notifications and dashboards.

Socket.IO

Socket.IO makes WebSockets easy and adds automatic reconnection, rooms and fallbacks. Install npm install socket.io on the server and use the client library in the browser.

Key methods

  • io.on('connection', socket => ...) — a client connected
  • socket.on('event', handler) — receive
  • socket.emit('event', data) — send to this client
  • io.emit('event', data) — send to everyone
  • socket.broadcast.emit(...) — everyone except the sender
  • socket.join('room1') and io.to('room1').emit(...) — rooms (group chats, per-order updates)
  • socket.on('disconnect', ...)

Validate data from clients just like HTTP input, and check login (for example a JWT in the handshake) before joining private rooms.

For simple one-way updates, Server-Sent Events are a lighter alternative.

Example

Example — Minimal chat server JavaScript
// server.js
import express from 'express';
import { createServer } from 'node:http';
import { Server } from 'socket.io';

const app = express();
const server = createServer(app);
const io = new Server(server);

app.get('/', (req, res) => res.sendFile(import.meta.dirname + '/index.html'));

io.on('connection', (socket) => {
  socket.broadcast.emit('system', 'A user joined the chat');

  socket.on('chat', (text) => {
    const message = String(text).slice(0, 500);
    io.emit('chat', { id: socket.id.slice(0, 4), message, at: Date.now() });
  });

  socket.on('disconnect', () => io.emit('system', 'A user left'));
});

server.listen(3000, () => console.log('Chat on http://localhost:3000'));

/* index.html (client)
<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io();
  socket.on('chat', (m) => console.log(m.id + ': ' + m.message));
  socket.emit('chat', 'Hello everyone!');
</script> */

Open http://localhost:3000 in two tabs: a message sent in one appears in both instantly, and joining or leaving shows a system message to the others.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which sends an event to every connected client?

Exercise 2 True / False

WebSockets let the server push data without the client asking first.

Exercise 3 Fill in the Blank

Put sockets into groups with socket.___('room-name')

Frequently Asked Questions

Yes. Use an adapter such as the Redis adapter so events reach clients connected to other servers, and enable sticky sessions on the load balancer.