Recent Messages and Recovering Missed Messages

Store recent room messages, query them automatically after rejoining, and avoid duplicate display using message IDs.

🎯 Introduction

While User A is disconnected, User B sends two messages to room1. The previous article lets A reconnect and rejoin; now A also needs to retrieve the missed messages. This article adds recent-message storage on the server and automatic retrieval after A joins successfully.


🧱 Save Messages Before Broadcasting to the Room

The server keeps the latest 20 messages per room. Each record has an ID that stays the same whether delivered in real time or returned by a history query. The client uses it to determine whether the message has already been displayed.

Import randomUUID at the top of server.mjs and define histories outside the connection callback so all clients access the same room records.

import { randomUUID } from 'node:crypto';

const histories = new Map();

Map associates room names with message arrays, and randomUUID() generates message IDs. After the identity, room, and text checks pass in chat:send, replace the original broadcast and successful acknowledgement with:

const room = socket.data.room;
const message = {
    id: randomUUID(),
    senderId: socket.data.userId,
    text: text.trim()
};
const items = histories.get(room) || [];
items.push(message);
histories.set(room, items.slice(-20));
io.to(room).emit('chat:message', message);
reply({ ok: true, id: message.id });

If no history exists, start with an empty array. push adds a message, and slice(-20) retains only the last 20. After saving, broadcast the same message object to the room.

This uses process memory, so restarting the server clears the records. Messages beyond the most recent 20 are also removed. This example can recover only messages still within that window.

🛠 Add a History Query Event

Add this listener inside the same connection callback. The client is already authenticated, but each query still checks current room permissions.

socket.on('chat:history', (reply) => {
    if (typeof reply !== 'function') {
        return;
    }
    const room = socket.data.room;
    if (!room || !canAccess(socket.data.userId, room)) {
        reply({ ok: false, error: 'Join a room you have permission to access first' });
        return;
    }
    reply({ ok: true, messages: histories.get(room) || [] });
});

The server uses socket.data.room to select the room to query. Returning an empty array when there are no records lets the client handle it as a normal query result.


🔄 Retrieve History Automatically After Joining

Continue editing User A's client.mjs from the previous article. Remove the original chat:message listener and replace it with this code, sharing a display function between live and historical messages.

const seen = new Set();

function showMessage(message) {
    if (seen.has(message.id)) {
        return;
    }
    seen.add(message.id);
    console.log(`[User ${message.senderId}] ${message.text}`);
}

socket.on('chat:message', showMessage);

Set stores unique values. Here, check the message ID first and return if it was already displayed; otherwise, record the ID and print the message. The same client process retains seen across reconnections. Stopping and restarting the process creates an empty set again.

Next, define a query function outside the connect listener.

function loadHistory() {
    socket.timeout(3000).emit('chat:history', (error, result) => {
        if (error) {
            console.log('History query timed out');
            return;
        }
        if (!result.ok) {
            console.log(result.error);
            return;
        }
        result.messages.forEach(showMessage);
    });
}

Finally, replace the original connect listener with the following code. Both initial connections and reconnections query history after successfully joining.

socket.on('connect', () => {
    socket.timeout(3000).emit('room:join', room, (error, result) => {
        if (error) {
            console.log('Joining room timed out');
            return;
        }
        if (!result.ok) {
            console.log(result.error);
            return;
        }
        console.log(`Joined ${result.room}`);
        loadHistory();
    });
});

Listen for live messages first, join the room next, then query history. This also captures new messages arriving during the query. If a record arrives both through a push and in query results, showMessage prints it only once. This example prints in arrival order, so overlapping live and historical messages may appear out of their original send order.


❓ Questions and Answers

Q1: Why do two submissions with identical text still display two messages?

Each submission generates a new message ID, representing a separate record. Deduplication here prevents the same record from appearing twice. Preventing duplicate storage caused by send retries additionally requires a stable request ID for each submission and server-side deduplication.

Q2: How can messages survive a server restart?

Store records in a database, then broadcast and acknowledge only after a successful write. Read history from the database in ordered pages and track the client's reading position to cover disconnections longer than the latest 20 messages.


🧪 Exercise

Restart the server once after updating it, then keep it running throughout the experiment. User B uses the authentication chapter's client that sends after joining room1.

ActionWhat User A should see
Start A, then have B send “First”Receive [User B] First in real time
Stop A, change B's text, and restart B to send “Second”A is stopped and cannot receive pushes
Restart AAutomatically retrieve “First” and “Second” after joining

The last step restarts A's process, clearing its local deduplication set, so it displays both retained records. To test deduplication separately, call loadHistory twice consecutively in the successful join callback. After restarting A, each record should still appear only once. Restore a single call after testing.


🎉 The client can now retrieve recent messages after joining and avoid displaying the same message twice.