ShareDB: Realtime JSON OT Database Backend

5.2.2 · active · verified Wed Apr 22

ShareDB is a powerful realtime database backend built on Operational Transformation (OT) for JSON documents, enabling concurrent multi-user collaboration and synchronous editing with eventual consistency. It is the core realtime backend for the DerbyJS web application framework. Currently in version 5.2.2, ShareDB maintains a consistent release cadence with frequent patch and minor updates addressing bugs and performance improvements. Key features include realtime query subscriptions, easy integration with various databases (like MongoDB via `sharedb-mongo`), horizontal scalability through pub/sub, document projections, middleware support for access control, and offline change syncing. It supports both server-side and browser environments and provides access to historic document versions and realtime user presence syncing. It differentiates itself by offering a complete OT-based solution for collaborative data management.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a basic ShareDB server with in-memory storage and pub/sub, integrated with a WebSocket server. It initializes the backend, connects a WebSocket server, and shows how to create a document using a ShareDB connection.

import { Backend, MemoryDB, MemoryPubSub } from 'sharedb';
import WebSocket from 'ws';
import http from 'http';

const backend = new Backend({
  db: new MemoryDB(),
  pubsub: new MemoryPubSub()
});

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.end('ShareDB Server\n');
});

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

wss.on('connection', (ws) => {
  const stream = new WebSocket.WebSocketJSONStream(ws);
  backend.listen(stream);
});

server.listen(8080, () => {
  console.log('ShareDB server listening on http://localhost:8080');
  // Example: Create a new document via a connection
  const connection = backend.connect();
  const doc = connection.get('myCollection', 'myDocument');

  doc.fetch((err) => {
    if (err) throw err;
    if (doc.type === null) {
      doc.create({ message: 'Hello, ShareDB!' }, 'json0', () => {
        console.log('Document created:', doc.data);
      });
    } else {
      console.log('Document already exists:', doc.data);
    }
  });
});

// To run this, you'll need 'ws' and 'sharedb' installed.
// For the client-side stream, you might need 'rich-websocket-jsonstream' or similar.

view raw JSON →