DEV Community

Cover image for Mastering Real-Time Collaborative Editing with Yjs and WebSockets
HexShift
HexShift

Posted on

Mastering Real-Time Collaborative Editing with Yjs and WebSockets

Mastering Real-Time Collaborative Editing with Yjs and WebSockets

Building a collaborative editing tool — like Google Docs — is an ambitious but incredibly rewarding project. In this article, we'll explore how to achieve real-time collaboration in the browser using Yjs, a CRDT (Conflict-free Replicated Data Type) library, combined with WebSockets to sync shared state across users.

Why Yjs?

Yjs is a powerful framework for real-time collaboration. It handles conflict resolution, offline editing, and syncs efficiently. Unlike operational transformation (OT) algorithms, Yjs uses CRDTs that naturally converge without the need for a central server to resolve conflicts.

Step 1: Setting Up the Project

mkdir yjs-collab
cd yjs-collab
npm init -y
npm install express ws yjs y-websocket

Step 2: Creating a WebSocket Server

// server.js
const http = require('http');
const WebSocket = require('ws');
const setupWSConnection = require('y-websocket/bin/utils.js').setupWSConnection;

const server = http.createServer();
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws, req) => {
  setupWSConnection(ws, req);
});

server.listen(1234, () => {
  console.log('WebSocket server running on ws://localhost:1234');
});

Step 3: Setting Up the Frontend

// index.html
<!DOCTYPE html>
<html>
<head>
  <title>Yjs Collaborative Editor</title>
</head>
<body>
  <textarea id="editor" style="width:100%; height:300px;"></textarea>
  <script type="module">
    import * as Y from 'https://cdn.skypack.dev/yjs';
    import { WebsocketProvider } from 'https://cdn.skypack.dev/y-websocket';
    import { yTextAreaBinding } from 'https://cdn.skypack.dev/y-textarea';

    const doc = new Y.Doc();
    const provider = new WebsocketProvider('ws://localhost:1234', 'room-1', doc);
    const yText = doc.getText('shared-text');

    const textarea = document.getElementById('editor');
    yTextAreaBinding(yText, textarea);
  </script>
</body>
</html>

Step 4: Testing It Out

Open the HTML file in multiple tabs or browsers. All users will see real-time updates as they type into the shared textarea.

Advanced Ideas

  • Integrate with CodeMirror or Monaco Editor for rich collaborative coding
  • Add user awareness (cursors, names, colors) via y-protocols/awareness
  • Persist shared state with LevelDB or MongoDB
  • Integrate auth for permissioned access to documents

Conclusion

Yjs and WebSockets provide a powerful foundation for building collaborative tools with minimal complexity. Whether you're building a shared editor, a whiteboard, or a note-taking app — this tech stack offers the scalability and flexibility you need.

If this guide helped you, consider supporting my work: buymeacoffee.com/hexshift

Top comments (0)