How to Build a Real-Time Collaboration App Using WebSockets
Real-time collaboration apps—like Google Docs or Figma—depend on instant data exchange. WebSockets provide a persistent, full‑duplex communication channel between client and server, making them ideal for live editing, chat, or shared whiteboards. This tutorial walks you through the core architecture, from setup to deployment.
To begin, you need a WebSocket server (Node.js with `ws` library) and a client (plain JavaScript). Install the server-side package: `npm install ws`. On the client, use the native `WebSocket` object. The server listens for connections, and each connection is a persistent socket.
1. Set Up the WebSocket Server
Create a Node.js file (e.g., `server.js`):
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', (ws) => {
console.log('Client connected');
ws.on('message', (message) => {
// Broadcast to all clients
wss.clients.forEach(client => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
Key points:
- Each client gets a unique `ws` object.
- Broadcasting sends the message to every connected client.
- Handle errors and disconnection with `ws.on(‘close’)`.
2. Build the Client Side
In your HTML, connect and handle messages:
const socket = new WebSocket('ws://localhost:8080');
socket.onmessage = (event) => {
// Update UI with received data
document.getElementById('output').innerText = event.data;
};
document.getElementById('sendBtn').onclick = () => {
socket.send(document.getElementById('input').value);
};
3. Manage State & Conflict Resolution
For true collaboration (e.g., text editing), you need operational transformation (OT) or CRDTs. A simpler approach: send JSON with `{ type: ‘edit’, position, text }`. The server broadcasts it, and clients apply the change locally. For production, use libraries like Yjs or ShareDB.
4. Scale with Connection Management
Use rooms/channels to separate documents. On connection, the client sends a `joinRoom` message. The server stores `ws` per room and only broadcasts within that room. This prevents irrelevant data from reaching users.
Building a real-time collaboration app with WebSockets is straightforward for basic sync. Add a lightweight backend (Express) to handle authentication and room creation. For complex features (cursor presence, undo history), integrate a CRDT framework. Start with a simple chat or whiteboard—once the WebSocket flow works, scaling to collaborative editing is just a matter of data structure.