Skip to content

Packages

Replication API

Sync JSON between apps in a few lines, or mirror existing cores and files.

Content reviewed 19 October 2026

Copy JSON data between apps with openCollection. It creates storage, discovers peers and wires replication for you. One app writes; the other apps keep read-only copies.

Write in one app

js
import { openCollection } from '@unstoppable-stack/p2p/data'
const notes = await openCollection({ storage: './notes' })
await notes.put('welcome', { text: 'Hello!' })
console.log({ key: notes.key, version: notes.version })
// Keep the app running while the other app syncs.

Read in another app

Pass the printed key and version through your app’s sharing flow. Dataset keys permit reading; share them only with intended readers.

js
import { openCollection } from '@unstoppable-stack/p2p/data'
const notes = await openCollection({ storage: './notes-copy', key })
await notes.sync({ version })
console.log(await notes.get('welcome')) // { text: 'Hello!' }
await notes.close()

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

sh
mkdir sync-demo
cd sync-demo
npm init -y
npm install @unstoppable-stack/p2p@0.6.0-alpha.3
# Save the program below as mirror.mjs, then run:
node mirror.mjs

This complete program runs two app instances, prints the copied value and cleans up its temporary data. Public discovery needs UDP network access; the wait fails after 60 seconds if the peer cannot be reached.

js
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { openCollection } from '@unstoppable-stack/p2p/data'

// Two app instances. In real apps retain their separate storage directories.
const directory = await mkdtemp(join(tmpdir(), 'p2p-mirror-'))
let writer, reader
try {
  writer = await openCollection({ storage: join(directory, 'writer') })
  await writer.network.ready() // Wait for public announcement before sharing.
  await writer.put('note', { text: 'Hello from another app' })

  // Transfer key + version using your app's trusted sharing channel.
  reader = await openCollection({ storage: join(directory, 'reader'), key: writer.key })
  await reader.sync({ version: writer.version, timeoutMs: 60_000 })
  console.log(await reader.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 reader?.close() } finally {
    try { await writer?.close() } finally { await rm(directory, { recursive: true, force: true }) }
  }
}

Everyday API

  • openCollection({ storage, key? }): create a dataset or join a shared key. On later opens, just storage reopens the saved dataset. Use one directory per dataset and device.
  • put(key, json) and del(key): write locally on the original writer. Copies reject writes. get(key) reads local data; sync before reading a fresh copy. Missing entries and stored JSON null both return null.
  • sync({ version, timeoutMs?, signal? }): download all blocks through a known writer version. The default timeout is 10 seconds; the maximum is 120 seconds. Cancellation and close stop the wait.
  • key and version: share these with another app. Get a newer writer version and sync again to guarantee later changes. This API does not subscribe to or acknowledge future writes.
  • close(): release owned storage and networking. Call it on each app at shutdown. Reopening retains downloaded data for offline reads.

What sync confirms

A local-downloaded receipt confirms that this device has the requested blocks. It is not proof of remote backup. Dataset-key discovery is separate from RPC pairing and grants; revoking an RPC grant does not revoke already shared data keys.

Run on two devices

sh
# On Device A, from the repository root.
npm run device --prefix examples/p2p-data -- mirror-host ./notes-writer

# On Device B, replace KEY and VERSION with Device A’s SHARE values.
npm run device --prefix examples/p2p-data -- mirror-read ./notes-reader KEY VERSION

Install the same package version and examples on both devices. Device A prints SHARE after announcing and must stay running. Device B prints DOWNLOADED after receiving the note. Ctrl+C closes the host safely; directories are retained for reopening.

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.

js
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: mirror existing cores and files

syncPack replicates Hypercores, Hyperbees and Hyperdrives and keeps seeding registered resources after the owner disconnects. It shares the P2P package's connection lifecycle. These reference pages describe published 0.6.0-alpha.2.

js
import { syncPack } from '@unstoppable-stack/p2p/sync'

// Add this pack to createNode({ capabilities: [...] }).
const sync = syncPack({ store: appStore })
// A host without a store can use syncPack({ storage: './.replicas' }).

// After pairing with the host and receiving sync grants:
await peer.call('sync', 'manifest.replace', {
  manifest: { schemaVersion: 1, resources: [
    { id: 'notes', kind: 'hyperbee', key: dataCoreKey,
      name: 'Notes', protection: { mode: 'mirror' } }
  ] }
})
const status = await peer.call('sync', 'status')
const { bytes } = await peer.call('sync', 'usage')

Methods and ownership

  • manifest.replace replaces the caller's complete resource set; omitted resources are unregistered. An empty list removes all its registrations. It is not a merge or disk purge.
  • status reports only the calling peer's cores, drives and protection state. usage reports its logical replicated bytes, not physical host disk use.
  • pause and resume act on the caller's resource set and persist across restart. Their scope is discovery-and-mirroring; existing replication channels may still transfer data. Personal Node uses an admit(ownerKey) callback for quota checks.
  • peek.core and peek.drive are bounded diagnostics, excluded from default grants. They do not provide generic file downloads or database queries.
  • Ownership follows the authenticated peer key. Two installations of one app have separate resource sets. Persisted manifests resume replication after host restart.

Manifest and protection contract

Version 1 manifests accept up to 128 resources with unique ids and 32-byte hex keys, supported kind, name and optional bounded string metadata. Protection defaults to metadata-only. mirror requests a full copy of the observed core length or drive version. Only locally checked checkpoints become protected; this does not promise future writes or independently tested recovery.

Restore remains a separate contract

Apps write to their local stores and drives first. Ordinary replication can retrieve data when its keys and availability are known. Dedicated file reads/ranges, selective path sync, full encrypted archives, identity recovery and purge controls are not built-in services.

Need help? Report an issue with your CLI version, platform, command and first relevant error.