Skip to content
Edytor
Esc
↑↓navigate↵open⌘Jpreview
On this page

Persistence

Keep documents in the browser with IndexedDB, work offline, sync open tabs, and clear the local copy.

Edytor persists documents in the browser’s IndexedDB. Use createIndexeddbSync for a local-only document, or rely on the local copy that createWebsocketSync keeps by default. This page covers both, plus offline behavior and cross-tab sync.

Local-only documents

A view with a room and no server stores the document under that name and restores it on the next visit:

<script lang="ts">
  import { Edytor } from 'edytor';

  const value = { children: [{ type: 'paragraph', content: [{ text: 'First note' }] }] };
</script>

<Edytor room="notes/today" {value} />

value is the content of a brand-new document only. When the store already holds the document, the stored content wins and value is ignored. The same works without a view:

import { createDocument, createIndexeddbSync } from 'edytor';

const value = { children: [{ type: 'paragraph', content: [{ text: 'First note' }] }] };
const document = createDocument();
document.attachSync(createIndexeddbSync('notes/today'), { value });

Every edit is written as it happens. Past 500 stored updates, the provider writes one compacted snapshot and drops the rows it replaces. The browser database is named edytor-v14-g11:<name> (each schema generation keeps its own, and an earlier one is left as it was). A new store starts empty: an earlier generation’s store is not converted (a document a room keeps takes its state from the room; one stored only in the browser starts empty).

Every row holds an update in the engine’s one (columnar) encoding; the snapshot is also gzip-compressed (CompressionStream), typically a fifth to a tenth of its uncompressed size. The edits written between snapshots stay one row each.

The local copy of a WebSocket document

A view with a server keeps an IndexedDB store beside the socket, so a synced document also survives reloads. With an actor, the view names it edytor:<actor.id>@<server>/<room>, and without one edytor:<server>/<room>; trailing slashes are removed from server in both, so wss://x/rooms/ and wss://x/rooms share one store. The factory form sets the name yourself:

import { createWebsocketSync } from 'edytor';

const sync = createWebsocketSync({
  server: 'wss://rooms.example.com/rooms',
  room: 'doc-42',
  persistName: `${userId}:doc-42` // optional; see "One user per browser profile"
});
Option Default Description
persist true Keep a local copy. false makes the sync the socket alone.
persistName edytor:<server>/<room> The local store’s name. Trailing slashes are removed from server.

Where there is no indexedDB (Node, Workers, SSR), the store is skipped and the sync is the socket alone. With a store, the socket dials once the store has loaded: the dial names the epoch of the document the copy holds (re-seeds), so a copy of an earlier epoch is handed over, never merged into the room’s.

Offline behavior

  • Starting offline. When the local copy holds the document, the document is ready at once from it, with no server. When the store is empty, the document waits for the store’s answer, then for the server’s answer or the readiness bound (1 s), before it seeds value. The bound starts when the socket opens or first fails to, so a slow or cold server (one still loading the room when you dial) is waited for, up to the connect timeout (connectTimeout, 10 s by default), and its content hydrates the document instead of racing a seed. Raise connectTimeout for rooms that take longer to load.
  • Refused. A server that refuses the client (close 1008, or 4xxx other than 4401) never gets a seed: an empty document stays pending and reports syncRefusal until that provider is released or syncs again.
  • Expired credentials. A 4401 before the first sync holds the seed too: the room may hold content, so an empty document waits for a dial that gets in. Refresh the token in params (onSyncExpired on <Edytor>, onExpired on createWebsocketSync); a token that is never refreshed leaves the document pending.
  • Editing offline. Every edit is written to the local copy. Closing every tab loses nothing.
  • Reconnecting. On every connection the client and the room exchange what the other lacks, so edits made offline, including those restored from the local copy after a reload, reach the room without any replay logic on your side.
  • Knowing it is saved. The WebSocket provider reports when the room has stored your edits; see saved state.
  • Re-seeded meanwhile. When the room re-seeded the document while the device was away, the reconnecting client hands its document over: the room merges its edits into the new epoch, then the client loads the new epoch into a new document (an <Edytor> that owns its document does it by itself) and its local copy starts over. A copy older than the cuts the room keeps (30 days) cannot merge: the room closes it 4410 too, and its edits are dropped with it.
  • Offline for more than 30 days. The room purges content deleted more than 30 days ago, from itself and every client. A device that comes back after that keeps its edits to content that still exists; what it typed into content deleted and purged meanwhile is dropped. See the purge.

Prefetch and last updated

A document opened offline shows what its local copy holds. To keep documents the user has not opened fresh (a list of recent pages, before a flight), prefetch syncs one document’s local copy with its room once and closes:

import { lastUpdated, prefetch } from 'edytor';

let fetchedAt = 0; // when this device last fetched the document
const target = { server: 'wss://rooms.example.com/rooms', room: 'doc-42', params: { token } };
const changed = await lastUpdated(target); // ms since the epoch, or null
if (changed !== null && changed > fetchedAt) {
  const { updated } = await prefetch(target);
  fetchedAt = Date.now();
}
  • prefetch(options) takes the createWebsocketSync options (server, room, params, persistName, WebSocketPolyfill, connectTimeout, maxBackoffTime, maxFrameBytes) and a timeout (30 s). It opens the local copy (edytor:<server>/<room> unless persistName names another, the name a view with an actor uses: edytor:<actor.id>@<server>/<room>), dials the room once, takes what the room has that the copy lacks and hands the room what the copy has that it lacks (edits made offline), waits until the room stored them, then closes both. It publishes no presence. It resolves with { updated } (whether the room sent anything new) and rejects with the room’s refusal (SyncRefusedError), after timeout, or where there is no IndexedDB.
  • lastUpdated(options) (server, room, params, and an optional fetch) asks the room when it last stored a change, in milliseconds since the epoch (null for a room that has stored no change since it began recording them, with this release), with one HTTP request that opens no document: a GET <server>/<room>?lastUpdated (the ws scheme turned into http) that routeDocumentSocket authorizes like a dial. It throws on an HTTP error (403 refused, 401 expired). Compare it with when you last fetched the document to decide whether to prefetch it.

First paint from a snapshot

A first visit to a room’s document (nothing in the local copy yet) shows nothing until the room answered. Pass the document as JSON in snapshot and the view shows it at once, read-only, then replaces it with the live, editable view as soon as its own document is ready:

<script lang="ts">
	import { Edytor, documentSnapshot } from 'edytor';

	let { data }: { data: { token: string } } = $props();
	const target = { server: 'wss://rooms.example.com/rooms', room: 'doc-42', params: { token: data.token } };
</script>

{#await documentSnapshot(target) then snapshot}
	<Edytor {...target} snapshot={snapshot ?? undefined} />
{/await}
  • documentSnapshot(options) (server, room, params, and an optional fetch) reads the room’s document as JSON with one HTTP request, a GET <server>/<room>?snapshot that routeDocumentSocket authorizes like a dial. It resolves with null for a room that stores nothing yet and throws on an HTTP error (403 refused, 401 expired). Call it in a server load (any fetch works there) and the first HTML holds the document; a room’s own code can pass read() instead.
  • snapshot is read once. The snapshot view renders the same plugins and block handles as the live one, read-only, inside [data-edytor-snapshot]; nothing in it is written to the document. A view whose document is ready at mount (a local copy that holds the document, a value without a room) never shows it.
  • The live view replaces it in one update with what the room holds, which is newer than the snapshot when someone edited in between.

Cross-tab sync

Tabs of the same document sync with each other over a BroadcastChannel, with or without a server:

  • createIndexeddbSync tabs sync through the store’s channel.
  • With createWebsocketSync, the local store carries the channel. An edit heard from another tab is relayed to the server on this tab’s socket, so an offline tab’s edits are saved as soon as any tab of the room is online. A socket the room made read-only relays nothing: it only sends this tab’s own edits, which the room denies.
  • Without a local store (persist: false, or no IndexedDB), the socket provider opens the channel itself.

disableBc: true on createWebsocketSync turns cross-tab sync off for both the socket and the store. Presence is shared across tabs too; a tab that closes announces its departure.

Clear the local copy

clearDocument(name) deletes a stored document. Destroy the document (or unmount the view that owns it) first, so no provider holds the database open:

import { clearDocument, createWebsocketSync } from 'edytor';

const sync = createWebsocketSync({ server: 'wss://rooms.example.com/rooms', room: documentId });
// ...later, at sign-out, after the editor is gone:
if (sync.persistName) await clearDocument(sync.persistName);

For createIndexeddbSync(name), pass the same name. sync.persistName is undefined when the sync keeps no local copy. After a re-seed (4410), createWebsocketSync deletes its copy itself: the deletion waits until every tab let go of the database, so a tab still writing the previous epoch writes into the copy that goes.

One user per browser profile

IndexedDB and BroadcastChannel are shared by every tab of a browser profile. Treat the local copy and the channel as belonging to one user:

  • With the edytor room, each CRDT client id belongs to the user whose socket dials with it. Edits a socket delivers under an id another user owns are stripped (the socket stays open), and edits it relays under an id the room has never seen are stored but stay unowned: delivering an id never makes it yours. See replicas.
  • If one browser profile hosts several accounts, give each user their own persistName, and a distinct room or disableBc: true so tabs of different users don’t share the channel. Or clear the local copy at sign-out.

Advanced: the provider class

IndexeddbPersistence is exported for code that manages a CRDT document itself:

import * as Y from 'edytor/crdt';
import { bindCrdt } from 'edytor/crdt/edytor';

const crdt = bindCrdt(Y);
const doc = crdt.createDoc();
const provider = new crdt.providers.IndexeddbPersistence('notes/today', doc, {
  awareness: new crdt.Awareness(doc),
  disableBc: false
});
provider.on('load-error', (error) => console.error(error));
await provider.whenSynced;
Event Payload When
synced (provider) Stored content has been applied.
load-error (error, provider) The store belongs to another generation or failed to load; whenSynced rejects.
failed (error, provider) The provider can never sync (for example, destroyed before loading).
schema-mismatch (detail, provider) Content with a foreign schema stamp was refused.
protocol-mismatch (mismatch, provider) A tab of another edytor generation sent a message; it was dropped.
message-error (error, provider) A message could not be read or a write failed.

provider.destroy() closes the database without deleting it. Most apps never need this class: prefer createIndexeddbSync with a document.

Was this page helpful?