Skip to main content
Implementing Real-Time Features with WebSockets

Implementing Real-Time Features with WebSockets

Andrius LukminasAndrius LukminasJanuary 3, 20266 min read565 views

The Use Cases

Several features required real-time updates:

  • Notification toasts when events occur
  • Live chat between users
  • Real-time dashboard metrics
  • Collaborative editing indicators

Architecture Decision: Socket.IO

We chose Socket.IO over raw WebSockets for its:

  • Automatic reconnection handling
  • Room-based messaging (perfect for chat)
  • Fallback to long-polling if WebSocket fails
  • Built-in acknowledgments

Server Setup

The WebSocket server runs alongside Next.js:

import { Server } from 'socket.io';

const io = new Server(server, {
  cors: {
    origin: process.env.NEXT_PUBLIC_APP_URL,
    credentials: true,
  },
});

io.on('connection', (socket) => {
  // Authenticate via session cookie
  // Join user-specific rooms
  // Handle events
});

Client Integration

A React context provides the socket instance to components:

const { socket, connected } = useSocket();

useEffect(() => {
  socket?.on('notification', handleNotification);
  return () => socket?.off('notification', handleNotification);
}, [socket]);

Scaling Considerations

For multi-server deployments, we use Redis as the Socket.IO adapter to share events across instances.

Related Articles

Comments

0/5000 characters

Comments from guests require moderation.