Packages
Collaborative databases
Shared JSON data with managed storage, explicit writers and deterministic conflict handling.
Content reviewed 19 October 2026
Use openCollaborativeDatabase for a shared JSON key-value database. Storage, discovery, replication and the reducer are included. You explicitly approve which devices can write.
Create, approve, write
import { openCollaborativeDatabase } from '@unstoppable-stack/p2p/data'
const alice = await openCollaborativeDatabase({ storage: './alice' })
const bob = await openCollaborativeDatabase({ storage: './bob', key: alice.key })
await alice.members.add(bob.writerKey)
await bob.waitFor(state => state.writable)
await bob.put('note', { text: 'Hello from Bob!' })
// At app shutdown: await bob.close(); await alice.close()In separate apps, share Alice’s database key with Bob, then verify Bob’s writer key before admitting it on Alice’s app. Knowing a database key permits reading but never automatically grants writing. The founder alone manages membership.
Experimental alpha.2 API
Install @unstoppable-stack/p2p@0.6.0-alpha.3 to use the /data helpers. Node 20+ is required for these examples; collaborative storage also needs autobase@7.28.2. P2P remains experimental.
Run it locally
mkdir database-demo
cd database-demo
npm init -y
npm install @unstoppable-stack/p2p@0.6.0-alpha.3 autobase@7.28.2
# Save the program below as collaborate.mjs, then run:
node collaborate.mjsThis complete program waits for Alice to observe Bob’s edit, prints it, and closes both instances. It uses real public discovery, needs UDP access and bounds its waits to 60 seconds.
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { openCollaborativeDatabase } from '@unstoppable-stack/p2p/data'
const directory = await mkdtemp(join(tmpdir(), 'p2p-collaborate-'))
let alice, bob
try {
alice = await openCollaborativeDatabase({ storage: join(directory, 'alice') })
await alice.network.ready() // Local open remains usable without a network.
bob = await openCollaborativeDatabase({ storage: join(directory, 'bob'), key: alice.key })
// Verify Bob's writer key through your app's trusted sharing channel.
await alice.members.add(bob.writerKey)
await bob.waitFor(state => state.writable, { timeoutMs: 60_000 })
await bob.put('note', { text: 'Written by Bob' })
// update() processes available history, not a global synchronization barrier.
const deadline = Date.now() + 60_000
while (await alice.get('note') === null) {
if (Date.now() > deadline) throw new Error('Alice did not receive the edit in time')
await new Promise(resolve => setTimeout(resolve, 50))
await alice.update()
}
console.log(await alice.get('note'))
} catch (error) {
console.error(error.code || 'ERROR', error.message)
if (error.network) console.error('Network status:', JSON.stringify(error.network))
process.exitCode = 1
} finally {
try { await bob?.close() } finally {
try { await alice?.close() } finally { await rm(directory, { recursive: true, force: true }) }
}
}
Reads, writes and conflicts
put(key, json),get(key),del(key): use JSON values without writing a reducer. Entry keys contain 1–1024 characters; operations are limited to 64 KiB. Missing entries and stored JSON null both read as null.- Concurrent replacements and deletes use Autobase’s deterministic operation order. The last operation in that order wins; this is not wall-clock ordering or character-level text merging.
- Writes return local-applied receipts. Reads use the local view.
update()processes available history; it is not a barrier that waits for all remote changes. members.add/remove(writerKey): founder-only writer management. A new writer is not an administrator or indexer. Removal propagates with history and cannot erase downloaded copies.watch(callback)observes local state and returns an unsubscribe function.waitFor(predicate, { timeoutMs, signal })waits for a synchronous state condition, such as writable.- Reopen with storage alone: the key is retained automatically. Use a dedicated directory per dataset and device.
close()releases all owned resources and is safe to call twice.
Experimental collaborative storage
The founder is the sole indexer, so stable progress can depend on it returning online. Encryption keys, when used, must be supplied on every open and shared securely. Lost-admin recovery, key rotation, schema migrations and complete backup are not provided. For custom conflict rules, use the adapter API below.
Run on two devices
# On Device A, from the repository root.
npm run device --prefix examples/p2p-data -- db-host ./alice
# On Device B, replace KEY with Device A’s DATABASE key.
npm run device --prefix examples/p2p-data -- db-join ./bob KEYDevice A prints DATABASE. Device B joins and prints WRITER. Verify that writer key, then paste it into Device A’s terminal and press Enter to approve. Keep both apps running until Device A prints OBSERVED. Ctrl+C closes safely without deleting data.
Public discovery and troubleshooting
Validation update, 20 October 2026: published 0.6.0-alpha.2 passed replication and collaborative writer approval between separate processes on one Mac using default public discovery on a home network. The reader downloaded its note and the founder observed the collaborator’s edit. Two physical devices and different networks remain unverified.
await data.network.ready({ timeoutMs: 60_000 })
console.log(data.network.status())
// { closed, announced, connections, dhtPeers }Here data is your collection or collaborative database. Local open stays usable offline. network.ready waits for a successful DHT announcement before you share a host’s key; it does not confirm a peer connection. Disconnected discovery retries with backoff. announced records a successful announcement during this session, not continuous connectivity.
- DATA_NETWORK_TIMEOUT with dhtPeers: 0: check internet access, network/VPN/firewall UDP policy and bootstrap reachability. Working DNS or web browsing does not prove UDP works. Public bootstrap nodes use UDP port 49737.
- DHT peers present but no connection: verify both apps use the same dataset key and the host is still running. Check peer connectivity on both networks; some NAT/network combinations cannot connect.
- Connected but waiting for data: verify the writer version, or approve the collaborator’s writer key on the founder. A local write receipt does not prove the other device received it.
- There is no HTTP/WebSocket fallback and no guarantee of connectivity on every network. Try another permitted network if UDP is blocked. Local tests and separate processes on one machine do not establish cross-device acceptance.
Advanced: custom views and reducers
Prototype with explicit engine opt-in
The /db prototype is available in published 0.6.0-alpha.2. Install autobase@7.28.2 explicitly to use it. The root P2P import does not load it, and ordinary consumers do not install this optional peer automatically. This prototype is separate from the existing experimental Autobee scaffold.
Applications supply a deterministic reducer and local view. Autobase orders writer logs so devices can converge after offline edits; application rules still decide what conflicting edits or deletes mean.
autobaseAdapter({ openView, apply, validate, closeView })defines application-owned view behavior.openDatabase({ node, store, adapter, key, encryptionKey })opens a local database and attaches replication to the P2P swarm.append(operation)accepts a bounded JSON operation and returns a local-applied receipt. db.view provides application queries;update()processes available data without claiming every peer is caught up.members.add(writerKey)andmembers.remove(writerKey)are restricted to the founding writer. New writers are non-indexers and receive no membership administration rights.state(),watch(callback)andwaitFor(predicate, { timeoutMs, signal })expose local progress. Signed system checkpoints do not prove that a remote host retained every application resource.close()releases this database's discovery lease, view and child store session. Close databases before their node and root store; other sockets and caller-owned stores remain available.
Distributed data boundaries
Local writes can proceed offline, while stable progress depends on available indexers. Reducers must be replayable and deterministic. Writer removal takes effect as history synchronizes; it does not erase downloaded data or rotate encryption keys. Pairing at the RPC layer does not grant database write authority.
Real tests cover offline conflict convergence, writer admission/removal, encrypted reconstruction from a retained reader and coexistence with RPC on a paired P2P connection. They do not establish complete backup, lost-admin recovery, automatic schema migration or multi-writer plus Personal Node sync support.