API Reference - @liveblocks/yjs

@liveblocks/yjs is a Yjs provider enabling you to use Liveblocks as the hosted back end of your realtime collaborative application. Read our getting started guides to learn more.

Setup

To set up Yjs, it’s recommended to use getYjsProviderForRoom. It’s no longer recommended to use LiveblocksYjsProvider directly, as issues may happen when dynamically switching between rooms.

React

In React, pass your room object with useRoom. It’s fine to use this function in your React components. From here, you can access your Y.Doc.

import { useRoom } from "@liveblocks/react";import { getYjsProviderForRoom } from "@liveblocks/yjs";
function App() { const room = useRoom(); const yProvider = getYjsProviderForRoom(room); const yDoc = yProvider.getYDoc();
// ...}

JavaScript

In JavaScript, pass the room retrieved with client.enterRoom.

import { createClient } from "@liveblocks/client";import { getYjsProviderForRoom } from "@liveblocks/yjs";
const client = createClient({ // Options // ...});
const { room, leave } = client.enterRoom("my-room-id", { // Options // ...});
const yProvider = getYjsProviderForRoom(room);const yDoc = yProvider.getYDoc();

getYjsProviderForRoom

Gets the current or creates a new LiveblocksYjsProvider for a room—this is the recommended way to use Yjs. This provider will automatically be cleaned up when the room is destroyed, so you don’t need to destroy the provider manually. The second argument is the LiveblocksYjsProvider options.

import { getYjsProviderForRoom } from "@liveblocks/yjs";
const yProvider = getYjsProviderForRoom(room, { // Options // ...});
const yDoc = yProvider.getYDoc();
Returns
Arguments
  • roomRoomRequired

    The Liveblocks room, retrieved with useRoom or client.enterRoom.

  • options.autoloadSubdocsbooleanDefault is false

    This option will load subdocs automatically.

  • options.enablePermanentUserDatabooleanDefault is false

    This option enables Yjs permanent user data class used by some libraries for tracking changes by author.

  • options.offlineSupport_experimentalbooleanDefault is false

    Experimental. Enable offline support using IndexedDB. This means the after the first load, documents will be stored locally and load instantly.

  • options.useV2Encoding_experimentalbooleanDefault is false

    Experimental. Use V2 encoding.

LiveblocksYjsProvider

LiveblocksYjsProvider is a Yjs provider that allows you to connect a Yjs document to Liveblocks. Any changes you make to the document will be stored on Liveblocks servers and synchronized with other clients in the room.

You can connect by creating a Yjs document, then passing it to LiveblocksYjsProvider along with the currently connected Liveblocks room.

import * as Y from "yjs";import { createClient } from "@liveblocks/client";import { LiveblocksYjsProvider } from "@liveblocks/yjs";
const client = createClient({ publicApiKey: "",});
const { room, leave } = client.enterRoom("your-room-id");
// Create Yjs document and providerconst yDoc = new Y.Doc();const yProvider = new LiveblocksYjsProvider(room, yDoc, { // Options // ...});
Arguments
  • roomRoomRequired

    The Liveblocks room, retrieved with useRoom or client.enterRoom.

  • yDocY.DocRequired

    The Y.Doc for the document.

  • options.autoloadSubdocsbooleanDefault is false

    This option will load subdocs automatically.

  • options.enablePermanentUserDatabooleanDefault is false

    This option enables Yjs permanent user data class used by some libraries for tracking changes by author.

  • options.offlineSupport_experimentalbooleanDefault is false

    Experimental. Enable offline support using IndexedDB. This means the after the first load, documents will be stored locally and load instantly.

  • options.useV2Encoding_experimentalbooleanDefault is false

    Experimental. Use V2 encoding.

LiveblocksYjsProvider.getYDoc

Returns the current room’s root Y.Doc.

// Root Y.Doc for the roomconst yDoc = yProvider.getYDoc();

LiveblocksYjsProvider.awareness

The awareness instance attached to the provider.

// Yjs awarenessconst awareness = yProvider.awareness;

LiveblocksYjsProvider.destroy

Cleanup function. Destroys the LiveblocksYjsProvider instance and removes all resources.

// Clean up yProvideryProvider.destroy();

LiveblocksYjsProvider.on("sync")

Add an event listener for the sync event. The sync event is triggered when the client has received content from the server. Can be used to fire events when the document has loaded.

// Listen for the sync eventyProvider.on("sync", (isSynced: boolean) => {  if (isSynced === true) {    // Yjs content is synchronized and ready  } else {    // Yjs content is not synchronized  }});

Aliased by LiveblocksYjsProvider.on("synced").

// "sync" and "synced" both listen to the same eventyProvider.on("sync", (sync: boolean) => /* ... */);yProvider.on("synced", (sync: boolean) => /* ... */);

LiveblocksYjsProvider.off("sync")

Remove an event listener for the sync event. The sync event is triggered when the client has received content from the server. Used to clean up LiveblocksYjsProvider.on("sync").

const handleSync = (synced: boolean) => {};yProvider.on("sync", handleSync);
// Clean up sync eventyProvider.off("sync", handleSync);

Aliased by LiveblocksYjsProvider.on("synced").

// "sync" and "synced" both listen to the same eventyProvider.off("sync", (sync: boolean) => /* ... */);yProvider.off("synced", (sync: boolean) => /* ... */);

LiveblocksYjsProvider.once("sync")

Add a one-time event listener for the sync event. The sync event is triggered when the client has received content from the server. Can be used to fire events when the document has loaded.

// Listen for the sync event only onceyProvider.once("sync", (isSynced: boolean) => {  if (isSynced === true) {    // Yjs content is synchronized and ready  } else {    // Yjs content is not synchronized  }});

Aliased by LiveblocksYjsProvider.once("synced").

// "sync" and "synced" both listen to the same eventyProvider.once("sync", (sync: boolean) => /* ... */);yProvider.once("synced", (sync: boolean) => /* ... */);

LiveblocksYjsProvider.emit("sync")

Synchronously call each listener for the sync event in the order they were registered, passing the supplied arguments to each.

// Call each listener and pass `true` as an argumentyProvider.emit("sync", true);

Aliased by LiveblocksYjsProvider.emit("synced").

// "sync" and "synced" both listen to the same eventyProvider.emit("sync" /* , ... */);yProvider.emit("synced" /* , ... */);

LiveblocksYjsProvider.synced

Boolean. Returns whether the client is synchronized with the back end.

// Check if Yjs content is synchronized with the serverconst isSynced: boolean = yProvider.synced;

LiveblocksYjsProvider.connect

Does nothing, added for compatibility. Connections are handled by the Liveblocks client.

LiveblocksYjsProvider.disconnect

Does nothing, added for compatibility. Connections are handled by the Liveblocks client.

Awareness

LiveblocksYjsProvider instances have an awareness property, which is powered by Liveblocks Presence. You can pass it to various bindings which implement awareness, for example plugins that enable multiplayer cursors in text editors.

const yDoc = new Y.Doc();const yProvider = new LiveblocksYjsProvider(room, yDoc);
// Yjs awarenessconst awareness = yProvider.awareness;

Because awareness is part of presence, it’s also accessible with room.getPresence and useMyPresence under the __yjs property.

// Yjs awarenessconst awareness = room.getPresence().__yjs;

Awareness.doc

The Yjs document that the current awareness instance is attached to.

// The current Yjs documentconst yDoc: Y.Doc = awareness.doc;

Awareness.clientId

A unique number identifying which client this awareness object is attached to.

// A unique number representing the current userconst clientId: number = awareness.clientId;

Awareness.getLocalState

Get the current user’s awareness state.

// The current user’s awarenessconst localState: unknown = awareness.getLocalState();

Awareness.setLocalState

Set the current user’s awareness state. Accepts JSON-compatible objects.

// Set the current user’s awarenessawareness.setLocalState({  user: {    name: "Jonathan",  },});

Awareness.setLocalStateField

Set a single property in the current user’s awareness state. Accepts JSON-compatible objects, or null to remove a property.

// Set a single property on the current user’s awarenessawareness.setLocalStateField("user", { name: "Jonathan" });

Awareness.getStates

Returns a Map of states for each client, with each user’s unique clientId as the key.

// A Map of each user’s awareness stateconst states: Map<number, unknown> = awareness.getStates();

Awareness.states

A Map of states for each client, with each user’s unique clientId as the key.

// A Map of each user’s awareness stateconst states: Map<number, unknown> = awareness.states;

Awareness.meta

Provided for compatibility, but generally not necessary. This would be used for handling user awareness timeouts, but internally awareness uses Liveblocks Presence, and this handles it for you.

const meta: Map<number, { click: number; lastUpdated: number }> =  awareness.meta;

Awareness.destroy

Provided for compatibility, but generally not necessary. Cleanup function. Destroys the Awareness instance and removes all resources. Used internally by LiveblocksYjsProvider.

// Cleanup functionawareness.destroy();

Awareness.on("destroyed")

Provided for compatibility, but generally not necessary. Add an event listener for the destroy event. The destroy event is triggered when awareness.destroy has been called.

awareness.on("destroyed", () => {  // Awareness has been cleaned up});

Awareness.off("destroyed")

Provided for compatibility, but generally not necessary. Remove an event listener for the destroy event. The destroy event is triggered when awareness.destroy has been called. Used to clean up [Awareness.on("destroyed").]

const handleDestroy = () => {};awareness.on("destroyed", handleDestroy);
// Clean up destroy eventawareness.off("destroyed", handleDestroy);

Awareness.once("destroyed")

Provided for compatibility, but generally not necessary. Add a one-time event listener for the destroy event. The destroy event is triggered when awareness.destroy has been called.

awareness.once("destroyed", () => {  // Awareness has been cleaned up});

Awareness.emit("destroyed")

Synchronously call each listener for the destroy event in the order they were registered, passing the supplied arguments to each.

// Call each listener and pass `true` as an argumentawareness.emit("destroy", true);

We use cookies to collect data to improve your experience on our site. Read our Privacy Policy to learn more.