Documents
Collaborative Yjs documents attached to any subject. The database keeps an update log and a compacted snapshot, a private Realtime topic carries live edits and presence, and better-supabase/yjs connects a Y.Doc to both.
documents stores Yjs documents for any subject: the body of a page, the notes on a deal. Each document is one row per subject and name, an append-only log of Yjs updates, and a snapshot that compaction folds the log into. Editors send each edit to the log and broadcast it on the document's private Realtime topic, so other editors see it at once and a client that was offline catches up from the log.
The database never parses Yjs. It stores the updates as bytes and checks who may read and write: reading needs documents.read and the subject's read rules, editing needs documents.write and the subject's write rules, suggesting needs documents.suggest and the subject's read rules, and compacting needs the service role or documents.manage.
better-supabase add documents
pnpm add yjsThe block's entity is document (the documents table). Installing it registers document as a subject. Rename it with blocks.documents.names; parameter names, such as max_documents, keep the default noun.
Server code calls the documents instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useDocuments } = defineDataHooks(
"documents",
(db: AppDb) => db.documents,
);const rows = await db.documents.list({ limit: 50 }).orThrow();"use client";
import { useDocuments } from "@/lib/supabase/hooks";
const rows = useDocuments({ limit: 50 });Which document block
Six blocks store something a person could call a document. Pick the one that matches what the app does with it:
| Block | Use it for |
|---|---|
documents | Text several people edit at once, as Yjs updates with live presence |
drive | Files and folders people upload, share and move |
content | Entries an editor drafts and publishes, such as pages and posts |
ai-files | Files an AI chat reads or writes: attachments, generated files and the documents beside the chat |
knowledge | Text split into chunks with embeddings, so an assistant retrieves the passages that answer a query |
memory | What an agent remembers about a user, a team or a record between conversations |
The blocks combine: knowledge ingests an AI files upload, and AI documents keep their versions in versions, as these documents can.
Configure
blocks: {
documents: {
options: {
maxUpdateBytes: 262_144,
compactAfter: 500,
},
},
},| Option | Default | What it does |
|---|---|---|
topic | documents | The Realtime topic prefix; each document's topic is <topic>:<document id> |
maxUpdateBytes | 1048576 | The largest update push accepts (DOCUMENT_UPDATE_TOO_LARGE otherwise) |
compactAfter | 200 | The number of updates since the snapshot that enqueues a documents.compact job, with the queue module |
A document is created on the first open by someone who may edit the subject; a reader who opens a document that doesn't exist yet gets DOCUMENT_NOT_FOUND. Deleting a subject deletes its documents.
The provider
createDocumentProvider from better-supabase/yjs connects one Y.Doc to one document:
connect()opens the document, applies the snapshot and the updates after it, and joins the private topic.- Each local edit is stored with
push, then broadcast with its sequence number. Edits made while a push fails wait and are merged into one update. - When the channel reconnects, the provider pulls the updates after the last one it has and sends the edits that waited. Yjs ignores updates it already applied, so a repeat is harmless.
A reader (canWrite: false) receives edits and presence but never pushes. A reader with canSuggest: true, or an editor who calls setMode("suggest"), keeps local edits as a draft instead (hasDraft); submitSuggestion(summary) stores the draft as one suggestion. Pass mode: "suggest" to start in that mode. track(state) shares a presence state on the topic and members() returns everyone from the last sync.
yjs is an optional peer. The provider imports it on the first connect(), or takes the module as options.yjs. It only calls applyUpdate and mergeUpdates, and listens to the document's update event.
Compaction
Compaction merges the snapshot and the log into one state with Y.mergeUpdates, stores it and drops the updates it contains. Run it from the service role, in the documents.compact job or a scheduled sweep:
import { compactDocument } from "better-supabase/yjs";
const documents = createDocuments({ transport: serviceTransport });
for (const documentId of await documents.toCompact().orThrow()) {
await compactDocument({ documents, documentId }).orThrow();
}A client that pulls updates that compaction dropped gets the snapshot back with them, and starts from it.
Suggestions
A suggestion is a Yjs update that waits outside the log until an editor decides on it, so the document stays unchanged while the suggestion is open. Members get documents.suggest, so a member who can only read a subject can still suggest. Rename the permission like any other through modules.documents.permissions.suggest.
| Method | What it does |
|---|---|
suggest(documentId, update, summary?) | Stores an update as an open suggestion |
suggestions(documentId, { status? }) | Lists suggestions in open (the default), accepted, rejected, withdrawn or all |
decideSuggestion(id, decision, note?) | accepted appends the update to the log, rejected closes it, withdrawn is for the author |
Accepting stores the update with the author as its actor and returns its sequence number. The provider's acceptSuggestion(id) accepts, applies the update locally and broadcasts it, so the other editors receive it like any edit. Accepting or rejecting needs edit access; a decided suggestion can't change again (DOCUMENT_SUGGESTION_CLOSED).
Versions
With the versions module installed, saveVersion(documentId, state, label) saves the merged state as a version of subject type document, and versions(documentId) and version(documentId, versionId) read them back. To restore one, apply the saved state to a new Y.Doc and replace the editor's content in a transaction, so the restore is an edit that every editor receives.
const saved = await documents
.saveVersion(document.id, Y.encodeStateAsUpdate(doc), "Sent to legal")
.orThrow();Named versions are versions with a label. nameVersion(documentId, versionId, label) names or renames one, null removes the name, and versions(documentId, { named: true }) lists only the named ones. Each version also carries its source and whether it is frozen; a frozen version keeps its name (DOCUMENT_VERSION_FROZEN).
A document page in one read
documents.page({ organizationId, subjectType, subjectId }) opens the document and, with versions: true and suggestions: true, adds the version list and the open suggestions. Opening comes first because it creates the document for an editor; the other two reads run together afterwards. Versions need the versions module.
Errors
| Hint | When |
|---|---|
DOCUMENT_NOT_FOUND | The document doesn't exist, or the caller may not read it |
DOCUMENT_FORBIDDEN | The caller may not edit, suggest on or compact the document, or withdraw someone else's suggestion |
DOCUMENT_UPDATE_INVALID | The update is empty or not base64 |
DOCUMENT_UPDATE_TOO_LARGE | The update is larger than maxUpdateBytes |
DOCUMENT_COMPACT_INVALID | compact names a sequence number past the last update |
DOCUMENT_VERSION_NOT_FOUND | The version doesn't belong to the document |
DOCUMENT_VERSION_FROZEN | The version is frozen, so its name can't change |
DOCUMENT_SUGGESTION_NOT_FOUND | The suggestion doesn't exist, or the caller may not read its document |
DOCUMENT_SUGGESTION_INVALID | The decision isn't accepted, rejected or withdrawn |
DOCUMENT_SUGGESTION_CLOSED | The suggestion was already decided |
Events and hooks
open records document.created with organizationId, subjectType, subjectId, id and name. suggest records document.suggested, and the decisions record document.suggestion_accepted and document.suggestion_rejected, each with suggestionId, authorId and status as well. The before_document_create and after_document_create SQL hooks run around the insert.
Without the client
db.documents is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import * as Y from "yjs";
import {
createDocuments,
rpcTransport,
} from "better-supabase/blocks/documents";
import { createDocumentProvider } from "better-supabase/yjs";
const documents = createDocuments({ transport: rpcTransport(supabase) });
const doc = new Y.Doc();
const provider = createDocumentProvider({
documents,
client: supabase,
doc,
ref: { organizationId, subjectType: "page", subjectId: page.id },
onPresence: (members) => setEditors(members),
});
await provider.connect().orThrow();
await provider.track({ name: user.name, color: "#0a7" });
// Bind doc to an editor (Tiptap, Lexical, CodeMirror), then on unmount:
await provider.destroy();Last updated on
Content
Documents, posts, forms and the blocks that hold content.
Drive
Folders and files on the attachments module. Access is granted to users or teams and inherited down the tree, storage policies enforce it on the objects too, and versions, trash and share-links add revisions, a bin, stars, recent items and folder links.