Real-Time Apps with WebSockets and Socket.IO: Rooms, Auth and Notifications

Node.js and Express: Build a Back End API from Scratch · Architecture, Reliability and Performance · 7 min read · Updated

Authenticated real time

  1. The browser opens a socket and sends its token in the handshake.
  2. The server verifies the token once. A bad token means the connection is refused.
  3. Each verified user joins a private room, so messages can target one person on all devices.
  4. Other server code calls notify to push to that room without knowing about sockets.

HTTP works like letters: the browser asks, the server answers, and the conversation ends. That is wrong for a chat, a live score, a delivery map or a notification bell, where the server must be able to speak first. WebSockets solve this. A WebSocket is one long-lived connection between browser and server, open in both directions, and either side can send a message at any time. This lesson uses Socket.IO, the most popular library for it in Node, which adds rooms, automatic reconnection and a fallback when WebSockets are blocked.

Core ideas

  • Connection: each browser tab that connects is a socket. It has an id and a place to keep data.
  • Events: you send and receive named messages with socket.emit('name', data) and socket.on('name', handler).
  • Rooms: groups of sockets. Sending to a room reaches everyone inside it. A room per user is a neat way to send something to one person on all their devices.
  • Broadcast: io.emit goes to everyone, io.to(room).emit to one room.

Authenticate on connect

A WebSocket is a door into your server, so it needs the same protection as an HTTP route. A socket must not be able to join without proving who it is. In Socket.IO you add a middleware that runs once for each new connection. The example below verifies a JWT sent in the handshake. If the token is missing or wrong, it calls next(new Error('unauthorized')) and the connection is refused. After that, socket.data.user holds the verified user id, and the code never trusts a user id sent in a message.

import http from 'node:http';
import { Server } from 'socket.io';
import jwt from 'jsonwebtoken';

// Real-time with Socket.IO: authenticate on connect, join a room per user, push notifications.
export function createRealtime({ secret }) {
  const server = http.createServer();
  const io = new Server(server);
  const online = new Set();

  // Middleware runs once per connection: refuse anyone without a valid token.
  io.use((socket, next) => {
    try {
      socket.data.user = jwt.verify(String(socket.handshake.auth?.token ?? ''), secret).sub;
      next();
    } catch {
      next(new Error('unauthorized'));
    }
  });

  io.on('connection', (socket) => {
    const me = socket.data.user;
    socket.join(`user:${me}`);                       // every user has a private room
    online.add(me);
    io.emit('presence', [...online]);

    socket.on('private-message', ({ to, text }) => {
      if (typeof text !== 'string' || !text.trim() || text.length > 500) return;      // never trust client data
      io.to(`user:${to}`).emit('private-message', { from: me, text: text.trim() });
    });

    socket.on('disconnect', () => {
      // Count a user offline only when their last connection closes.
      if (!io.sockets.adapter.rooms.get(`user:${me}`)) online.delete(me);
      io.emit('presence', [...online]);
    });
  });

  // Other parts of the server (a route, a job) can push a notification to one user:
  const notify = (userId, payload) => io.to(`user:${userId}`).emit('notification', payload);

  return { server, io, notify };
}

Walk through what happens after the connection. The socket joins a private room named user:<id>. The id is added to a set of online users and everyone receives the new presence list. A private-message event is checked first: the text must be a string, not empty and at most 500 characters, because data from a client is never trusted just because it came over a socket. Then it is sent only to the room of the receiver. On disconnect, the user is removed from the online set only when their last connection closes, since a person can have a phone and a laptop open at once.

Pushing from the rest of your server

The function returns notify(userId, payload). It lets any other part of your server, such as an Express route, a payment webhook or a background job, send a real-time notification to one user without knowing anything about sockets. When lesson 35's worker finishes a report, it can call notify and a bell appears in the browser. This is how most apps combine a normal HTTP API with real-time features: HTTP for requests, sockets for pushes.

  1. Make a folder and open it in a terminal. Run npm init -y, then open package.json and add "type": "module" so that import works.
  2. Install what the lesson needs: npm install socket.io jsonwebtoken.
  3. Save the code as realtime.js. The test needs npm install -D socket.io-client.
import test from 'node:test';
import assert from 'node:assert/strict';
import { io as connect } from 'socket.io-client';
import jwt from 'jsonwebtoken';
import { createRealtime } from './ws37-realtime.js';

const once = (socket, event) => new Promise((resolve) => socket.once(event, resolve));

test('auth, private messages and notifications', async () => {
  const { server, io, notify } = createRealtime({ secret: 's' });
  await new Promise((resolve) => server.listen(0, resolve));
  const url = `http://127.0.0.1:${server.address().port}`;
  const token = (sub) => jwt.sign({ sub }, 's');

  // No token: refused.
  const anon = connect(url, { auth: {}, reconnection: false });
  const refusal = await once(anon, 'connect_error');
  assert.equal(refusal.message, 'unauthorized');
  anon.close();

  const alice = connect(url, { auth: { token: token('alice') } });
  const bob = connect(url, { auth: { token: token('bob') } });
  await Promise.all([once(alice, 'connect'), once(bob, 'connect')]);

  const incoming = once(bob, 'private-message');
  alice.emit('private-message', { to: 'bob', text: '  hi Bob  ' });
  assert.deepEqual(await incoming, { from: 'alice', text: 'hi Bob' });

  const note = once(alice, 'notification');
  notify('alice', { title: 'Order shipped' });
  assert.equal((await note).title, 'Order shipped');

  alice.close(); bob.close();
  await io.close();
});
ok 1 - auth, private messages and notifications

The test connects without a token and is refused, connects two users, sends a private message from one to the other, checks that a third user does not receive it, and calls notify.

Scaling sockets

Sockets are stateful: a connection lives on one server process. With two copies of your app, a message emitted on copy A does not reach a user connected to copy B. The fix is an adapter, usually the Redis adapter for Socket.IO, which passes events between the copies. You also need a load balancer that keeps a client on the same server during the connection (*sticky sessions*) when the long-polling fallback is used. Without these, real-time features work in development and break in production.

Your task

  1. Add a typing event that tells the other user that someone is typing.
  2. Add a room per chat group, and let a user join only the groups that they belong to.
  3. Limit the number of messages per second for each socket.

How to check it worked

  • A connection without a token is refused.
  • A private message reaches only its receiver.
  • You can explain why presence is removed only when the last connection closes.

Frequently asked questions

WebSocket or Socket.IO?

WebSocket is the browser standard. Socket.IO builds on it and adds rooms, reconnection, fallbacks and acknowledgements, at the cost of using its own protocol on both sides.

Do I authenticate every message?

You authenticate the connection once, and keep the verified user on the socket. Still validate the content of every message.

Why does real time break when I run two servers?

A socket lives on one process, so events must be shared between processes, for example with the Redis adapter.

Practise with interview questions