How to use Yjs subdocuments

Liveblocks Yjs supports subdocuments, which allow you to nest Yjs documents inside each other. This guide takes you through how to use them on client and server.

When to use subdocuments

Subdocuments are helpful when you have multiple large Yjs documents in the same room, and you wish to lazy-load them individually. Each subdocument works similarly to a normal Yjs document, allowing you to use shared types, awareness, and more.

Not necessary for multiple text editors

Please note that subdocuments are not necessary for displaying multiple text editors on one page. For this use case, it’s often best to create a Y.Map in your Yjs document, and place the contents of each editor inside. For example, if your text editor uses Y.XmlFragment, here’s how to create this.

This is much simpler than using subdocuments. However, if the content of these editors is very large, or if your text editor only accepts a Y.Doc, subdocuments may be for you.

On the client

Subdocuments can be stored in your Yjs tree like any other shared type. In this example we’ll create a Y.Map to store them in, making sure to lazy load any subdocuments.

Create a subdocument

To create a new subdocument, create a new Y.Doc(), and use it like any other.

Make sure to keep track of its guid.

Load the subdocument

To load the subdocument on another client, use its guid.

Listening for changes

To keep track of subdocument changes, you can use Y.Doc.on("subdocs").

On the server

It’s possible to use your subdocument on the server, without connecting with a provider.

Fetching a subdocument

When fetching a Yjs subdocument on the server, it’s recommended to use liveblocks.getYjsDocumentAsBinaryUpdate with the guid of your subdocument. We stored the guid when we created the subdocument.

We’ve now retrieved the subdocument, and it can be read, but any changes you make won’t be applied to other clients, and are only temporary.

Updating a subdocument

To permanently apply changes to your subdocument, sending them to Liveblocks and other clients, you can use liveblocks.sendYjsBinaryUpdate.

After running this code, all connected users will see the update.