Yjs IndexedDB Persistence

9.0.12 · active · verified Tue Apr 21

y-indexeddb is a database adapter for Yjs, providing robust persistence for Yjs documents directly within the browser's IndexedDB. It enables critical features such as offline editing and significantly reduces the amount of data exchanged between a server and client by storing the full document state locally. The package is actively maintained, with the current stable version being 9.0.12, and receives frequent patch and minor updates. Its primary differentiation lies in its tight integration with the Yjs ecosystem, offering reliable CRDT-based persistence for collaborative applications without requiring a separate server-side database, making it ideal for browser-based, offline-first applications leveraging Yjs.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates initializing a Yjs document with IndexedDB persistence and handling the 'synced' event to confirm data loading or initial content creation, including storing custom metadata.

import * as Y from 'yjs';
import { IndexeddbPersistence } from 'y-indexeddb';

const ydoc = new Y.Doc();
const docName = 'my-shared-document';

// Create a provider for IndexedDB persistence
const provider = new IndexeddbPersistence(docName, ydoc);

provider.on('synced', async () => {
  console.log('Content from the database is loaded.');
  // After content is loaded, you can safely interact with ydoc
  if (ydoc.getText('myText').length === 0) {
    ydoc.getText('myText').insert(0, 'Hello Yjs and IndexedDB!');
    console.log('Initial text set:', ydoc.getText('myText').toString());
  } else {
    console.log('Loaded text:', ydoc.getText('myText').toString());
  }

  // Example of storing custom metadata
  await provider.set('lastEdited', Date.now());
  console.log('Metadata stored:', await provider.get('lastEdited'));
});

// Clean up resources when the document is no longer needed
// Note: provider.destroy() is often automatically called if ydoc.destroy() is used.
// For demonstration, manually destroying after a delay:
// setTimeout(() => {
//   provider.destroy();
//   console.log('IndexedDB persistence destroyed.');
// }, 5000);

view raw JSON →