Skip to content

Your first React workspace

Build the repository with the source quick start first. The eleven @peerborne/* packages are unpublished workspaces. Use these files in a browser React/TypeScript project with @peerborne/core, @peerborne/automerge, @peerborne/react, React, and React DOM installed, as the next section shows. Automerge’s browser build also needs Vite’s WASM setup; the wiki example configuration shows the required plugins. This is a local document exercise, with no relay or second identity required.

Create the application outside the Peerborne checkout. Adding it as a workspace of the checkout changes the root yarn.lock, so yarn install --immutable then fails. Instead, pack the libraries as tarballs in the checkout and install them in the application:

Terminal window
# In the Peerborne checkout, after yarn install --immutable and yarn build.
# The directory must be outside the checkout; release:prepare replaces it.
yarn release:prepare ~/peerborne-packages
# In the application directory:
npm install ~/peerborne-packages/*.tgz react-dom
npm install --save-dev vite @vitejs/plugin-react vite-plugin-wasm typescript

release:prepare packs all eleven libraries and writes release-manifest.json beside the tarballs. Installing every tarball at once lets npm resolve the packages’ dependencies on each other, such as @peerborne/react on @peerborne/store, from those files rather than the registry. npm also installs their peer dependencies, including React and Automerge; React DOM is added explicitly. Repeat both steps after pulling new Peerborne sources. Release validation installs the tarballs the same way in a clean npm project.

The shipped hook uses explicit create initialization for this new document, subscribes to updates, and provides a mutation callback. With the Automerge adapter, that callback edits a typed JavaScript object. Remounting the component never founds another document: the hook keeps a document it created open while its changes have not reached a member, and otherwise opens the path again.

Workspace.tsx
import { usePeerborneDocumentState } from '@peerborne/react';
import type { WorkspaceNode } from './peerborne';
export function Workspace({ peerborne }: { peerborne: WorkspaceNode }) {
const [doc, change, , error] = usePeerborneDocumentState(peerborne, '/workspace', 'all', 'create');
if (!doc) return <p>{error ? 'Could not create workspace' : 'Opening…'}</p>;
return <button onClick={() => change((draft) => {
draft.title = 'Ready to ship';
})}>{doc.title ?? 'Name this workspace'}</button>;
}

usePeerborneDocumentState is the real exported API. The setup module below is application code supplied by this guide. There is no usePeerborneDoc export or one-call identity/session factory in the current packages.

Copy this module alongside the component. It selects Automerge, serializers, signing, ACLs, key management, and browser networking defaults. The context’s stateful caches are required for the hook to trigger React renders.

peerborne.tsx
import { useState, type ContextType, type ReactNode } from 'react';
import { PeerborneContext } from '@peerborne/react';
import {
Peerborne,
SubtleCrypto,
defaultConfig,
defaultBootstrapConfig,
} from '@peerborne/core';
import {
AutomergeProvider,
AutomergeJSONSerializer,
AutomergeACLProvider,
AutomergeKeychainProvider,
} from '@peerborne/automerge';
type WorkspaceData = { title?: string };
type SessionContext = ContextType<typeof PeerborneContext>;
export async function createWorkspaceNode() {
const keys = await crypto.subtle.generateKey(
{ name: 'ECDSA', namedCurve: 'P-384' },
false,
['sign', 'verify'],
);
const serializer = new AutomergeJSONSerializer();
const peerborne = new Peerborne(
keys.privateKey,
keys.publicKey,
new AutomergeProvider<WorkspaceData>(),
serializer,
serializer,
serializer,
new SubtleCrypto(),
new AutomergeACLProvider(),
new AutomergeKeychainProvider(),
);
await peerborne.initialize(defaultConfig(defaultBootstrapConfig([])));
return peerborne;
}
export type WorkspaceNode = Awaited<ReturnType<typeof createWorkspaceNode>>;
export function DocumentSessions({ children }: { children: ReactNode }) {
const [docCache, setDocCache] = useState<SessionContext['docCache']>({});
const [docDataCache, setDocDataCache] = useState<SessionContext['docDataCache']>({});
const [docReadersCache, setDocReadersCache] = useState<
SessionContext['docReadersCache']
>({});
const [docWritersCache, setDocWritersCache] = useState<
SessionContext['docWritersCache']
>({});
return (
<PeerborneContext.Provider
value={{
docCache,
setDocCache,
docDataCache,
setDocDataCache,
docReadersCache,
setDocReadersCache,
docWritersCache,
setDocWritersCache,
}}
>
{children}
</PeerborneContext.Provider>
);
}

This exercise creates a fresh, non-extractable signing key on every page load. A reload therefore creates a new identity. Before building a persistent application, design storage for the signing identity, the KEM key pair, and an encrypted checkpoint of each document, which holds its keys and state; see Identities. A document path alone does not give another client its keys or access.

Use an HTML entry point containing <div id="root"></div> and load this module:

main.tsx
import { createRoot } from 'react-dom/client';
import { createWorkspaceNode, DocumentSessions } from './peerborne';
import { Workspace } from './Workspace';
const root = createRoot(document.getElementById('root')!);
try {
const peerborne = await createWorkspaceNode();
root.render(
<DocumentSessions>
<Workspace peerborne={peerborne} />
</DocumentSessions>,
);
} catch {
root.render(<p>Could not initialize the local workspace. Reload to retry.</p>);
}

Click Name this workspace. The button becomes Ready to ship after the document subscription updates. The node starts once, outside the React render lifecycle.

change returns void and does not catch the change’s promise, so a rejection becomes an unhandled promise rejection. This compact component demonstrates the subscription API; use await document.change(...) with application error handling when a save action must report authorization, storage, or signing failures. A committed change that does not reach a member resolves and is reported as deliveryFailure instead. See the React integration guide for lifecycle details.

Pass your relay’s dialable multiaddr to defaultBootstrapConfig instead of an empty list; see Run your own relay. An empty bootstrap list creates a local node with no configured bootstrap peers. Connecting does not onboard a new identity. Use the current signed invitation flow to share with one online collaborator, and review its membership and recovery limits.

Opening the same path on another node is not onboarding either. The hook’s default 'open' mode loads from peers and requires resolveLoadSecurityCommitments and resolveTrustedDocumentWriters in the node configuration. If no connected peer can serve the path (a relay cannot), it reports No document state is available…; if one can and resolveLoadSecurityCommitments is missing, it reports a TrustedLoadSecurityCommitmentsError. See Open existing documents.

The component, setup, and entry point are stored as source files and checked together against the workspace APIs:

Terminal window
yarn build
node site/scripts/check-doc-snippets.mjs

For a runnable browser application, follow the source quick start.