Getting started
One package for the engine and the Blazor components, one for the transport, one for the relay - then a
BcrdtTextArea inside a BcrdtCollaborationScope is a working collaborative editor
with live presence, automatic reconnection and offline support.
Install
Bit.Bcrdt carries the engine, the synchronization, presence and persistence, the in-memory and
WebSocket transports and the Blazor components. The SignalR client transport is a package of its own with no
ASP.NET Core server dependency, so it runs in WebAssembly and Hybrid apps too. All four packages target .NET 10
and 11.
# the engine and the Blazor components dotnet add package Bit.Bcrdt # the SignalR transport - or use the WebSocket transport built into Bit.Bcrdt, or none dotnet add package Bit.Bcrdt.SignalR
| Package | Contents |
|---|---|
| Bit.Bcrdt | The engine - BcrdtText, BcrdtArray, BcrdtMap and BcrdtSet, updates, snapshots and selective undo - with presence, the in-memory, file-system and IndexedDB stores, the sync protocol, AddBitBcrdtServices, the input bindings, the in-memory and WebSocket transports, metrics, and the Blazor components: BcrdtCollaborationScope, BcrdtTextArea, BcrdtPresenceView and BcrdtComponentBase. |
| Bit.Bcrdt.SignalR | The SignalR client transport. |
| Bit.Bcrdt.Server | The ASP.NET Core relays - BcrdtHub for the SignalR transport and MapBitBcrdtWebSocket for the WebSocket transport - with per-document read-only or read-write access, and BcrdtDocumentHost, which keeps a stored replica of every document the relays carry. |
| Bit.Bcrdt.Testing | A deterministic, seeded network simulator, random operation generators, a convergence harness and an update corrupter for fuzzing - for testing a collaborative feature, or a type of your own, against loss, duplication, reordering and partitions. |
Register the services
Register it once, in every project that renders collaborative components - in a Blazor Web App, that is both the server and the client project. The .NET SignalR client needs an absolute hub URL, so resolve it against the host; in Blazor WebAssembly that is the host page's base address.
using Bit.Bcrdt; using Bit.Bcrdt.SignalR; string hubUrl = new Uri(new Uri(builder.HostEnvironment.BaseAddress), "hub/bcrdt").ToString(); builder.Services.AddBitBcrdtServices(collaboration => collaboration .UseTransport(new BcrdtSignalRTransportFactory(hubUrl)) .UseInMemoryStore());
AddBitBcrdtSignalRTransport(hubUrl) is the same registration as a one-liner. Each of the three
seams - transport, store and options - is optional: an application that configures none of them still gets a
working, purely local collaborative document, so a feature can be built and tested without a server and then
connected to one without changing how it reads or writes state.
| Seam | Choices |
|---|---|
| Transport | BcrdtSignalRTransportFactory (SignalR), BcrdtWebSocketTransportFactory (a raw WebSocket, built in), or any IBcrdtTransportFactory of your own. None: the document stays local. |
| Store | UseIndexedDbStore() in the browser - a document, and what was typed into it offline, survives a reload or a closed tab; UseStore(new BcrdtFileSystemDocumentStore("./documents")) on a server, the desktop or MAUI; UseInMemoryStore() for tests; or any IBcrdtDocumentStore. |
| Options | Configure(options => ...): how long presence lasts (PresenceTimeout, 30 s), heartbeat and reconnection timing (Sync), compaction (Persistence), whether deleted content is reclaimed (GarbageCollect), and whether each document gets a default undo stack. |
// The WebSocket transport instead: {documentId} is filled in per document. builder.Services.AddBitBcrdtServices(collaboration => collaboration .UseTransport(new BcrdtWebSocketTransportFactory("https://example.com/ws/bcrdt/{documentId}")) .UseIndexedDbStore());
Map the relay
The hub lives in a separate server-side package, so that the client transport carries no ASP.NET Core server
dependency. Use AddBitBcrdtHub rather than a bare AddSignalR: SignalR's default
32 KB receive limit is smaller than the handshake reply for any document of real size.
dotnet add package Bit.Bcrdt.Server # in the server project
using Bit.Bcrdt.Server; builder.Services.AddBitBcrdtHub(); // AddSignalR, with a receive limit sized for sync messages // ... app.MapHub<BcrdtHub>("/hub/bcrdt");
The raw WebSocket transport has its relay in the same package: call app.UseWebSockets() and map
it with app.MapBitBcrdtWebSocket("/ws/bcrdt/{documentId}"). On its own a relay only relays: a
document exists while somebody has it open. To keep every document on the server as well - so the first
person into an empty room still gets everything ever written into it - register a document host, as the
live page's server does:
builder.Services.AddBitBcrdtDocumentHost(_ => new BcrdtDocumentHostOptions { Store = new BcrdtFileSystemDocumentStore(Path.Combine(builder.Environment.ContentRootPath, "documents")), });
Who may join a document, and whether they may write, is decided by overriding
BcrdtHub.AuthorizeAccessAsync (or setting AuthorizeAccess on the WebSocket endpoint).
The live page shows a read-only link enforced that way.
A first editor
BcrdtCollaborationScope opens the document, renders its content with the document as context,
shows LoadingContent while it opens (and ErrorContent if it cannot), follows
DocumentId when it changes and releases the document when it goes away.
BcrdtTextArea turns every keystroke into the minimal edit and publishes the caret through
presence; BcrdtPresenceView lists who is here. There is no stylesheet to reference and no script
tag to add: the one small module the textarea needs is imported on demand.
@using Bit.Bcrdt @using Bit.Bcrdt.Blazor <BcrdtCollaborationScope DocumentId="notes-42" User="_me" Context="document"> <BcrdtPresenceView Presence="document.Presence" /> <BcrdtTextArea Text="@document.Text("body")" Presence="document.Presence" /> </BcrdtCollaborationScope> @code { private readonly BcrdtCollaboratorInfo _me = new("u-1", "Ada", BcrdtPresenceService.SuggestColor("u-1")); }
SuggestColor hashes a user id into a fixed palette, so every participant agrees on everyone's
colour without asking anyone. In a page that is prerendered and then becomes interactive, a document may only
be opened once the component is interactive (RendererInfo.IsInteractive) - one opened while
prerendering belongs to a request that is already over. BcrdtCollaborationScope waits for that by
itself. The live page is exactly this, across browser tabs.
A component of your own
Derive from BcrdtComponentBase - the base of the three components - to make any component
collaborative. Its Track overloads re-render the component whenever a type, a document, presence
or the connection changes, from anyone; they marshal the notification onto the renderer, coalesce bursts onto
a frame (RenderInterval, 16 ms) so five people typing do not cause hundreds of renders a second,
and unsubscribe when the component goes away.
@inherits BcrdtComponentBase <p>@_title.Count characters</p> @code { [CascadingParameter] public BcrdtCollaborativeDocument Document { get; set; } = default!; private BcrdtText _title = default!; protected override void OnParametersSet() { _title = Document.Text("title"); Track(_title); // re-render, coalesced, whenever the text changes - from anyone } }
Working with a document in code
Outside a component, IBcrdtCollaborationService is the whole API. OpenAsync loads the
document from the store first - so it is usable at once, and offline - then connects and lets the handshake
reconcile whatever changed meanwhile. Opening the same identifier twice returns the same instance, reference
counted, so pair every OpenAsync with a CloseAsync.
BcrdtCollaborativeDocument document = await collaboration.OpenAsync("board-7", new BcrdtOpenDocumentOptions { User = me }); using (var transaction = document.BeginTransaction()) // one update, one round of events { document.Map.Set("title", "Q3 planning"); document.Array("attendees").Push("Ada", "Grace"); document.Text("notes").Insert(0, "Agenda:\n"); } document.Changed += change => { /* every committed update, with its origin */ }; document.Text("notes").Observe((change, transaction) => { /* change.Delta */ }); await collaboration.CloseAsync("board-7");
- Connection.
ConnectAsyncandDisconnectAsynctake a document online and offline on purpose;ConnectionStatus,IsSyncedandSync.LastSyncedAtsay where it stands. A dropped connection is retried by itself. - Values. A document holds
null,bool,string, integers,double,float,decimal,byte[], dates,Guid, lists and string-keyed dictionaries of those, and nested collaborative types. Anything else is refused up front; an object of your own is flattened onto those withSetObject. - Threads. A document is not thread-safe. One opened through the service applies every network update on the synchronization context it was opened on - in Blazor, the renderer's.
- The engine alone.
document.Crdtis the replica itself, aBcrdtDocumentthat runs anywhere with no service at all - a console app, a worker, a test.
The internals page shows transactions, updates and change events as they happen.
Choose the data type
This is the decision that matters most: the merge is decided by the data structure rather than by your application, so it is worth knowing what each one will decide.
| Type | Concurrent edits resolve as | Reach for it when | See it |
|---|---|---|---|
| BcrdtText | Both edits survive, each author's run stays contiguous | Anything a person types into at length | Collaborative text, Rich text |
| BcrdtArray | Both insertions survive, in a stable order | Lists, ordered collections | Collaborative list |
| BcrdtMap | One value wins, deterministically but arbitrarily | Fields where a later value legitimately replaces an earlier one | Collaborative form |
| BcrdtSet | An add wins over a concurrent remove - if it added something (re-adding a present element is a no-op) | Tags, membership, flags | Collaborative form |
The trap is a BcrdtMap with a long string in it: two people editing that field concurrently
means one of them loses everything they typed. If a field is something a human types prose into, make it a
nested BcrdtText and both edits merge - the collaborative form shows the two
side by side.
document.Map.EnsureText("description").Insert(0, "..."); // merges document.Map.Set("description", "..."); // one side wins
The same caution applies to BcrdtArray.Replace and Move: both delete the element and
insert a new one, so an edit made to the element at the same time is lost, and two people moving one element
at once end up with two copies. Change a nested type in place when that matters. The
conflict lab runs each rule on purpose.
Every hosting model
The registration is the same everywhere, and IBcrdtCollaborationService is registered
scoped on purpose. In WebAssembly and Hybrid apps - MAUI, WPF, Windows Forms - there is one
scope, so each app is one replica. On Blazor Server each circuit is a scope, so every connected user gets a
replica and a client identity of their own; a singleton would make every visitor one replica. In a Blazor Web
App, register it in both projects: whichever side renders interactively owns the replica.
On Blazor Server a circuit outlives its browser tab for a while, and keeps publishing presence until it goes. To
withdraw a user the moment the connection drops, call builder.Services.AddBitBcrdtCircuitPresence()
from Bit.Bcrdt.Server: its CircuitHandler calls document.Presence.Suspend()
on every open document when the connection goes down, and Resume() when it comes back. The engine
needs no JavaScript at all, so it runs as well in a background service or a console app. Outside AOT builds, a
WebAssembly app can also lazy load the library instead of registering it.
Lazy loading on WebAssembly
A WebAssembly app can fetch Bcrdt only when someone opens a part of the app that collaborates. It then cannot
call AddBitBcrdtServices in the Program.cs of the project that runs in the browser,
and configures the collaboration service instead: IServiceProvider.GetBcrdtCollaborationService(...)
takes the builder AddBitBcrdtServices takes, and where no IBcrdtCollaborationService
is registered, BcrdtCollaborationScope - and the Collaboration property of every
BcrdtComponentBase - use the service it configured. That is WebAssembly only: everywhere else Bcrdt
is loaded with the app, so the registration is required there, and the components fail without it. Mark the
assembly as lazy loaded in the project that runs in the browser, and load it before the first page that uses it
renders:
<!-- The browser project's .csproj --> <ItemGroup> <BlazorWebAssemblyLazyLoad Include="Bit.Bcrdt.wasm" /> </ItemGroup>
@* App.razor - in a Blazor Web App, the client project's Routes.razor: the router waits for OnNavigateAsync before it renders the page. *@ @using Microsoft.AspNetCore.Components.WebAssembly.Services @inject LazyAssemblyLoader LazyAssemblyLoader <Router AppAssembly="typeof(App).Assembly" OnNavigateAsync="OnNavigateAsync"> ... </Router> @code { private async Task OnNavigateAsync(NavigationContext context) { // The pages that collaborate: fetch Bcrdt before they render. A second call loads nothing again. if (context.Path.StartsWith("notes", StringComparison.OrdinalIgnoreCase)) await LazyAssemblyLoader.LoadAssembliesAsync(["Bit.Bcrdt.wasm"]); } }
Those pages, or a layout only they use, configure the service in OnInitialized - which runs before
the components inside them ask for it - with what Program.cs would otherwise have registered:
@* NotesLayout.razor *@ @using Bit.Bcrdt @inherits LayoutComponentBase @inject IServiceProvider Services @inject NavigationManager Navigation @Body @code { protected override void OnInitialized() => Services.GetBcrdtCollaborationService(collaboration => collaboration .UseTransport(new BcrdtWebSocketTransportFactory(Navigation.BaseUri + "ws/bcrdt/{documentId}")) .UseIndexedDbStore()); }
- Leave
AddBitBcrdtServicesout of that project'sProgram.cs: calling it references Bcrdt's types before the assembly is there. For the same reason only what renders after the assembly has loaded may use Bcrdt's types - the pages it is loaded for and a layout only they use, notApp.razor,Routes.razor, a layout every page shares orProgram.cs. - No type in an assembly the router reads when the app starts - the app's own assembly first of all - may derive from or implement one of Bcrdt's: no component that inherits
BcrdtComponentBase, no transport, store or client id provider of your own. On WebAssembly such a type fails to load before Bit.Bcrdt is there, and keeps failing after it has loaded. Put it in a library that is lazy loaded together with Bit.Bcrdt. The router finds the routes of that library's pages only once it knows the assembly: load it in the sameLoadAssembliesAsynccall asBit.Bcrdt.wasm, and add the assemblies the call returns to a list theRouter'sAdditionalAssembliesis bound to. - Configure the service before anything asks for it: in
OnInitialized, not after anawaitinOnInitializedAsync, which lets the layout's content render first. A component that asks before anything configured the service throws, naming both ways to provide one; nothing is created by that, so a configuration that comes later - on the next page, say - still takes effect. - Only the first configuration creates the service, so a page visited again gets the same service back.
GetBcrdtCollaborationService(_ => { })configures a purely local one, with no transport and no store. - The builder's container holds the app's
IJSRuntime, soUseIndexedDbStore()works, and nothing else of the application's: hand the transport and the store over as instances or delegates. - With the SignalR transport, lazy load
Bit.Bcrdt.SignalR.wasmalong withBit.Bcrdt.wasm- and the SignalR client's own assemblies too, where nothing the app loads at startup uses them. - Do not lazy load in an AOT build. AOT compiles every assembly into
dotnet.native.wasm, so there is nothing left to download later, and lazy loading an AOT-compiled assembly can fail at startup.
In a Blazor Web App only the browser lazy loads; the server project loads Bcrdt with the rest of the app:
- The router has to run in the browser for
OnNavigateAsyncto load the assembly there: giveRoutestheInteractiveWebAssemblyorInteractiveAutorender mode inApp.razor. With per-page render modes the router and the layouts render statically on the server, soOnNavigateAsyncnever runs in the browser - and neither does a layout'sOnInitialized. - The server project still calls
AddBitBcrdtServices. Prerendering - and, withInteractiveAuto, the visits that run in a circuit - use that registration:GetBcrdtCollaborationService(...)returns it there without calling the configuration, so the same layout works on both sides. - The server project also registers
LazyAssemblyLoader, whichRoutes.razorinjects while it is prerendered there, and which loads nothing outside the browser:builder.Services.AddScoped<LazyAssemblyLoader>().
Where to go next
- Collaborative text - three replicas of one paragraph, presence and carets, and what happens when one goes offline or loses its connection.
- Collaborative list - a list of maps, where a rename and a tick of the same item both survive.
- Collaborative form - map entries, a set and a nested text, each merging its own way.
- Rich text - formatting marks that merge like any edit, read back as a delta.
- Conflict lab - eight conflicts provoked on purpose, each with its outcome stated before it runs.
- Collaborative undo - a stack per replica that undoes only its own edits.
- Version history - snapshots that rebuild the document as it was.
- Internals - state vectors, blocks, updates, deltas and metrics, measured live.
- Live, across tabs - one replica per browser tab through the demo server, with a read-only link.
- MCP server - point an AI agent at this site and it reads the real API, the guide and these pages.
- The full reference guide - persistence, presence, transports, security, extending the library, the architecture and the correctness tests - is the README on GitHub.