Building chat with Socket.IO and Next.js: bugs I hit in Sosifie
Text arrived instantly, images needed a reload, and typing showed in the chat but not the sidebar. Wiring Socket.IO, REST uploads and the client cache.

In Sosifie's chat, a text message showed up on the other screen right away, but a photo only appeared after a reload. Text went over Socket.IO, uploads went over REST, and the REST endpoint didn't emit anything to the recipient. Sosifie is a small social app I build alone: a Next.js web client, an Express API with Prisma on PostgreSQL, and chat with text, images, files, typing, read receipts and burn-after-read messages.
The REST controller has to emit too
Images and files go up as multipart POSTs to REST because multer and Cloudinary storage were already set up there, and I didn't want binary data in socket events. Splitting it that way is fine. The socket module now exports io through getIo(), and the send, delete and mark-read controllers all emit to the conversation room after the database write, as in io.to(conversationId).emit('receive_message', payload).
Socket and REST still don't emit the same way. The socket handler uses socket.to(room), which skips the sender, and confirms separately with a message_sent event that includes the real ID. The REST controller uses io.to(room), so a file you upload comes back to you as receive_message. The only thing preventing a duplicate is one client-side line, page.data.some(m => m.id === newMessage.id), and I don't like a whole behavior resting on one check.
The socket token ends up on the client
The API puts the access token in an HTTP-only cookie. The web app and API are on different origins, so I didn't trust the browser to send the cookie with the WebSocket handshake, and client JavaScript can't read it. The current version reads the cookie in the root layout (a Server Component) and passes the token down to SocketProvider as a prop, which puts it in io()'s auth.token. On the server, a Socket.IO middleware looks for the token in the cookie header, then handshake.auth.token, then handshake.query.token, verifies the JWT and attaches the user to the socket.
That has two weak spots. Passing the token as a prop throws away the point of HTTP-only. And the server only checks the token at handshake. An open connection keeps working after its token expires, until the next reconnect. If I redid it, I'd issue a short-lived socket ticket from a Route Handler so the session token is never sent to the client.
Typing has to reach the personal room
Each socket joins two kinds of room. The personal room is named after user_name, joined by the server on connection, and carries sidebar updates, notifications and unread counts. The conversation room is named after the conversation ID, and the client emits join_conversation when it opens a chat and leave_conversation when it leaves.
The first typing indicator only broadcast to the conversation room, so "typing" disappeared once you went back to the conversation list: you weren't in any chat room there. The server now also sends it to each other participant's personal room, with the conversation_id:
socket.on('typing', async (data: { conversation_id: string; is_typing: boolean }) => {
const payload = { conversation_id: data.conversation_id, user_name: user.user_name, is_typing: data.is_typing };
// 1. Active chat view
socket.to(data.conversation_id).emit('user_typing', payload);
// 2. Sidebar: every other participant's personal room
const conversation = await chatService.getConversationWithParticipants(data.conversation_id);
conversation?.participants.forEach((p) => {
if (p.user_name !== user.user_name) io?.to(p.user_name).emit('user_typing', payload);
});
});
The client keys its typing map by conversation_id, and each sidebar row reads typingUsers[convo.id]. With the chat open, the event arrives twice and sets the same boolean twice, which is harmless. The input only emits typing: true when the local isTyping flag flips, and a 2-second setTimeout, reset on every keystroke, sends typing: false. Each typing event still queries PostgreSQL for a participant list that almost never changes, so it needs a cache.
Read receipts and burn-after-read share one request
Opening a conversation calls POST /chat/:conversationId/mark-read. The service runs updateMany to mark everything the other side sent as read, then deleteMany to remove messages that have burnAfterRead set and are read. A normal unsend only sets isDeleted: true and replaces the content with "Message deleted". The controller emits messages_read with read_by, and the sender's screen edits the React Query cache directly instead of refetching:
const handleMessagesRead = (data: { conversation_id: string; read_by: string }) => {
if (data.conversation_id !== selectedConvoId) return;
queryClient.setQueryData([QUERY_KEYS.MESSAGES, selectedConvoId], (old: any) => {
if (!old) return old;
const pages = old.pages.map((page: any) => ({
...page,
data: page.data
.map((m: chat.Message) => (m.sender_name !== data.read_by ? { ...m, is_read: true } : m))
.filter((m: chat.Message) => !(m.burnAfterRead && m.is_read)),
}));
return { ...old, pages };
});
};
Both screens run the same filter, so one event removes the burned message on both sides. The weak part is that "read" here means "opened the conversation": markAsRead runs in an effect keyed on the selected conversation ID and never checks the viewport. A burn-after-read message that arrives while the chat is open stays there until the next time it's opened.
Optimistic updates and presence
sendMessage writes a temp-${Date.now()} message into the first page of the cache and emits send_message; when message_sent arrives, the handler removes the temp message and inserts the real one. It currently removes every temp- message because the ack doesn't include the temp ID, so if you send two messages quickly, the first ack hides the second one until its own ack arrives.
Online status is kept in a plain Map inside the API process:
// user_name -> Set of socket IDs (one user, many tabs)
const onlineUsers = new Map<string, Set<string>>();
// on connect: add socket.id; if it's the first one, broadcast 'online'
// on disconnect: remove socket.id; if the set is empty, broadcast 'offline'
A set per user instead of a boolean means closing one tab doesn't mark you offline while another is still open. But this Map and Socket.IO's rooms only exist in one process's memory. I'm inferring, not having tried it, that with two instances an event emitted on A won't reach a socket connected to B. The redis package is in package.json but nothing uses it yet.
What's left
The bugs that show wrong messages on screen come first: send the temp ID with send_message and return it in message_sent, and rejoin rooms on reconnect. The Expo app's hook already listens for connect and re-emits join_conversation, while the web hook only joins when the socket or selected chat changes, so after a reconnect you drop out of the conversation room.
The Redis adapter can wait. It only matters once the API runs a second instance.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.