Project 6: A Real-Time Chat Application

Node.js and Express: Build a Back End API from Scratch · Ten Portfolio Projects · 8 min read · Updated

Chat in two channels

  1. A socket connects with a token. A bad token is refused.
  2. The verified user joins a private room. Messages go to the room of the receiver.
  3. Every message is saved under the conversation key.
  4. Opening a chat loads the past from REST. New messages arrive over the socket.

Chat is the favourite real-time project, because you can see it work with two browser tabs. Under the screen there are three real questions. How do you know who is connecting? How do you deliver a message to exactly one person? And what happens to the messages when the person is offline? This project answers them with Socket.IO for live delivery and a normal REST route for history, which is how real chat apps are built: sockets for what is happening now, HTTP for what has already happened.

What you will build

  • Sockets that connect only with a valid JWT.
  • Private messages sent to one user, delivered to every device that they have open.
  • An online list that updates when people connect or leave.
  • Saved history for each pair of users.
  • GET /api/messages/:other that returns a conversation for the logged-in user.

Design decisions before any code

Each conversation has a key made from the two user ids in sorted order, so that alice:bob and bob:alice are the same thread. Messages are saved in a Map here and in a collection in a real system, with an index on the conversation key and the time. The sender of a message is always taken from the verified token on the socket, never from the message itself, because a message that says from: someone-else must not be believed.

This project builds on lesson 36. Read that first if the words *room* and *handshake* are new.

  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 express socket.io jsonwebtoken.
  3. Copy p-kit.js, p06-chat.js and p06.test.js into the folder. The shared p-kit.js is in Project 1.
  4. Install the test tools with npm install -D supertest socket.io-client, then run node --test p06.test.js.

The chat is created by createChat, which returns the HTTP server and the Socket.IO server together. Notice the connection counter: a user is offline only when the last of their sockets closes.

// Project 6: real-time chat. Private messages, online status, saved history and a REST endpoint to read it.
import http from 'node:http';
import express from 'express';
import { Server } from 'socket.io';
import jwt from 'jsonwebtoken';
import { SECRET } from './p-kit.js';

const pairKey = (a, b) => [a, b].sort().join(':');

export function createChat({ secret = SECRET } = {}) {
  const app = express();
  const server = http.createServer(app);
  const io = new Server(server);
  const history = new Map();       // "alice:bob" -> messages
  const connections = new Map();   // userId -> number of open sockets

  const verify = (token) => jwt.verify(String(token ?? '').replace(/^Bearer /, ''), secret);

  // REST: read a conversation (the same token rules as the socket).
  app.get('/api/messages/:other', (req, res) => {
    try {
      const me = verify(req.get('authorization')).sub;
      res.json(history.get(pairKey(me, req.params.other)) ?? []);
    } catch {
      res.status(401).json({ error: 'Log in first' });
    }
  });

  io.use((socket, next) => {
    try { socket.data.user = verify(socket.handshake.auth?.token).sub; next(); } catch { next(new Error('unauthorized')); }
  });

  io.on('connection', (socket) => {
    const me = socket.data.user;
    socket.join(`user:${me}`);
    connections.set(me, (connections.get(me) ?? 0) + 1);
    io.emit('presence', { user: me, online: true });
    socket.emit('online-users', [...connections.keys()]);

    socket.on('message', ({ to, text }, ack) => {
      const clean = typeof text === 'string' ? text.trim() : '';
      if (!to || !clean || clean.length > 500) return ack?.({ ok: false, error: 'Message must be 1 to 500 characters' });
      const message = { from: me, to, text: clean, at: new Date().toISOString() };
      const key = pairKey(me, to);
      history.set(key, [...(history.get(key) ?? []), message]);
      io.to(`user:${to}`).emit('message', message);          // reaches every device of the receiver
      ack?.({ ok: true });
    });

    socket.on('typing', ({ to }) => io.to(`user:${to}`).emit('typing', { from: me }));

    socket.on('disconnect', () => {
      const left = (connections.get(me) ?? 1) - 1;
      if (left <= 0) { connections.delete(me); io.emit('presence', { user: me, online: false }); } else connections.set(me, left);
    });
  });

  return { server, io };
}

The test connects two real Socket.IO clients to the server on a free port, and checks delivery, history and presence.

import test from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { io as connect } from 'socket.io-client';
import { createChat } from './p06-chat.js';
import { signToken } from './p-kit.js';

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

test('project 6: private chat, presence and history', async () => {
  const { server, io } = createChat();
  await new Promise((resolve) => server.listen(0, resolve));
  const url = `http://127.0.0.1:${server.address().port}`;
  const token = (id) => signToken({ id, role: 'user', name: id });

  const alice = connect(url, { auth: { token: token('alice') } });
  await once(alice, 'connect');

  const bobConnect = connect(url, { auth: { token: token('bob') } });
  const sawBob = once(alice, 'presence');
  await once(bobConnect, 'connect');
  assert.deepEqual(await sawBob, { user: 'bob', online: true });

  const received = once(bobConnect, 'message');
  const ack = await new Promise((resolve) => alice.emit('message', { to: 'bob', text: ' hello ' }, resolve));
  assert.equal(ack.ok, true);
  assert.equal((await received).text, 'hello');

  const bad = await new Promise((resolve) => alice.emit('message', { to: 'bob', text: '   ' }, resolve));
  assert.equal(bad.ok, false);

  const typing = once(alice, 'typing');
  bobConnect.emit('typing', { to: 'alice' });
  assert.equal((await typing).from, 'bob');

  const history = await request(server).get('/api/messages/alice').set('Authorization', `Bearer ${token('bob')}`);
  assert.equal(history.body.length, 1);
  assert.equal((await request(server).get('/api/messages/alice')).status, 401);

  const offline = once(alice, 'presence');
  bobConnect.close();
  assert.deepEqual(await offline, { user: 'bob', online: false });

  alice.close();
  await io.close();
});

Rules worth understanding

Authenticate once, on connect. The handshake middleware verifies the JWT. A bad token means the connection is refused, so no code that runs afterwards has to wonder who the user is.

Validate every message. A message must be a text, not empty and not too long. Anything else is ignored. Never trust the content just because it came through a trusted connection.

Many tabs, one user. A person may have a phone and a laptop open. Each is a socket in the same private room, so a message reaches both. The online list uses a counter per user, so closing one tab does not make a person look offline.

History through HTTP. When a user opens a conversation, the front end loads the saved messages with a normal request and then listens on the socket for new ones. HTTP is easy to cache, page and secure with the same middleware as the rest of your API.

Security and honesty notes

Escape message text when you draw it, because a chat is a perfect place for the cross-site scripting of lesson 30. Limit the message size and the number of messages per second for each user, or one client can flood the room.

With more than one server process, you need the Redis adapter of Socket.IO so that events pass between them, as lesson 36 explains. This project runs in one process.

Extend it

Your task

  1. Add a typing event that is sent to the other person.
  2. Add read receipts: a message is marked read when the receiver opens the thread.
  3. Add group rooms with a membership list that the server checks before joining.

How to check it worked

  • A socket without a token is refused.
  • A message reaches only its receiver.
  • A user with two tabs stays online until both close.

On your resume. "Built a real-time chat with Socket.IO, JWT-authenticated sockets, private rooms, presence and persistent history" shows that you can handle more than plain REST. Write only what you really built and can explain, and keep the repository link next to it. Our resume templates have a project section that suits this, and the ATS checker shows how a tracking system reads it.

Frequently asked questions

Why use both sockets and REST?

Sockets are best for live events. REST is simple, cacheable and secure for loading the past. Real chat apps use both.

How do I know who sent a message?

From the token that was verified when the socket connected. Never from a field in the message.

What changes with several servers?

Use the Redis adapter, so events pass between server copies, and a load balancer that supports WebSockets.

Practise with interview questions