Real-Time Features with Socket.IO and React: Rooms, Auth and Clean-Up
By Muhammad Osama Khan, Software Engineer. Real-time, Sep 1, 2026, 4 min read.
A chat-style example: a Socket.IO server with JWT auth and rooms, and a React hook that connects, joins, listens and cleans up properly.
HTTP requests are one-way: the browser asks, the server answers. For chat, live notifications or collaborative boards you want the server to push updates the moment they happen. Socket.IO gives you that over WebSockets, with automatic reconnection and fallbacks, and it fits neatly beside an Express API.
The server: auth, rooms and events
Attach Socket.IO to the same HTTP server as Express. Use a middleware to check the token before the connection is accepted, and put each conversation in a room so you can send an event to just the people in it.
server/realtime.js
import http from 'http';
import { randomUUID } from 'node:crypto';
import express from 'express';
import jwt from 'jsonwebtoken';
import { Server } from 'socket.io';
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: process.env.CLIENT_URL, credentials: true }
});
// runs once per connection: reject anyone without a valid token
io.use((socket, next) => {
try {
socket.user = jwt.verify(socket.handshake.auth.token, process.env.JWT_ACCESS_SECRET);
next();
} catch {
next(new Error('Unauthorized'));
}
});
io.on('connection', (socket) => {
socket.on('room:join', (roomId) => {
// check here that socket.user is allowed in this room
socket.join(roomId);
socket.to(roomId).emit('room:presence', { userId: socket.user.sub, online: true });
});
socket.on('message:send', ({ roomId, text }, ack) => {
const message = {
id: randomUUID(),
roomId,
userId: socket.user.sub,
text: String(text).slice(0, 2000),
at: Date.now()
};
io.to(roomId).emit('message:new', message); // everyone in the room, including the sender
ack?.({ ok: true, id: message.id });
});
});
server.listen(4000);- Verify the token in
io.use, not inside each event handler, so an unauthenticated socket never gets that far. - Always check that the user may join the room before calling
socket.join. Room names are guessable. - Treat everything from the client as untrusted: limit message length, validate the shape, and save the message to your database before you emit it.
The client: a React hook
Wrap the connection in a hook so components stay simple. The effect creates the socket, registers listeners and, most importantly, cleans up after itself.
src/hooks/useRoom.js
import { useEffect, useRef, useState } from 'react';
import { io } from 'socket.io-client';
export function useRoom(roomId, token) {
const socketRef = useRef(null);
const [messages, setMessages] = useState([]);
const [connected, setConnected] = useState(false);
useEffect(() => {
const socket = io(import.meta.env.VITE_API_URL, { auth: { token } });
socketRef.current = socket;
// 'connect' also fires after every automatic reconnect, so the room is re-joined for free
socket.on('connect', () => {
setConnected(true);
socket.emit('room:join', roomId);
});
socket.on('disconnect', () => setConnected(false));
socket.on('message:new', (message) => setMessages((prev) => [...prev, message]));
return () => {
socket.off('message:new');
socket.disconnect();
};
}, [roomId, token]);
const send = (text) =>
socketRef.current?.emit('message:send', { roomId, text }, (res) => {
if (!res?.ok) console.error('Message was not delivered');
});
return { messages, connected, send };
}Why the clean-up matters
Without the return function, every re-render or route change leaves an old socket and its listeners alive. You then receive each message several times. React's Strict Mode in development mounts effects twice on purpose, which is a useful way to catch exactly this bug: with the clean-up in place, you still see each message once.
Before you ship it
- Persist messages in your database and load history over a normal HTTP route. Sockets deliver live events; they are not storage.
- Scaling: with more than one server instance, add the Redis adapter (
@socket.io/redis-adapter) so an event emitted on one instance reaches clients connected to another. - Sticky sessions: if clients may fall back to HTTP long polling, the load balancer must send a client to the same instance each time.
- Handle offline: use the
connectedflag to show a banner, and keep the send button disabled or queued while disconnected.
Frequently asked questions
What are rooms in Socket.IO?
Rooms are named groups of sockets on the server. A socket joins a room with socket.join(name), and io.to(name).emit(...) sends an event only to the sockets in it. They are the usual way to build chat channels or per-document updates.
How do I authenticate a Socket.IO connection?
Send the token in the auth option of the client (io(url, { auth: { token } })) and verify it in an io.use middleware on the server using socket.handshake.auth.token. Reject the connection there so unauthenticated sockets never reach your event handlers.
Why do I receive the same Socket.IO message more than once in React?
Usually listeners or sockets are not cleaned up. Create the socket inside useEffect and return a function that removes the listeners and disconnects it, so re-renders and route changes do not leave old connections running.
Do I need Redis to scale Socket.IO?
If you run more than one server instance, yes: use an adapter such as @socket.io/redis-adapter so an event emitted on one instance reaches clients connected to another. A single instance does not need it.