Local-first with barrel-lite
This project runs two TypeScript clients, a phone and a laptop, each with its own local copy of one database, synced with a barrel_server. The phone writes and reads locally, syncs, goes offline and keeps editing, while the laptop edits the same document. Back online, both versions are kept as a conflict; the phone resolves it once and the resolution reaches the laptop and the server. Use it when an app must keep working without the network.
Prerequisites
-
Node 22.6 or later (this run used Node 22.19).
main.tsruns with Node's type stripping, no build step. -
A running barrel_server (1.13 or later) on
BARREL_URL, defaulthttp://localhost:8080, with no auth. See the server quickstart. -
barrel-lite, built from the barrel repository. It is not on npm yet:
cd /path/to/barrel/clients/barrel-lite npm install && npm run build cd - npm install npm install --no-save /path/to/barrel/clients/barrel-lite
Run
BARREL_URL=http://localhost:8080 ./run.sh
run.sh type-checks main.ts with tsc --noEmit, then runs it. The
program deletes and recreates the database lf_groceries on the
server so every run starts empty.
What it shows
Database.open(name, {remote, storage}): in Node the local store isMemoryAdapter; in a browser the default is OPFS.putandgetwork on the local copy, with no request.sync()pushes local changes, then pulls the server's.- Offline is simulated with the
remote.fetchoption: a fetch that fails makessync()throw aSyncErrorwith codenetwork; the local writes wait and go up on the next sync. - Two concurrent edits of one document are both kept:
getreturns one,conflictsreturns the other.resolvereplaces both, here and, after a push, everywhere. queryruns BQL locally over the synced copy.
Notes
- Local data in
MemoryAdapteris gone when the process exits. In a browser, OPFS keeps it, flushed every 200 ms; sync is what makes it durable. - The browser runs (OPFS, several tabs) are covered by barrel-lite's own Playwright suite, not by this example.
Expected output
One line per step. The output of a real run is in expected.txt.
Download The folder on GitHub, with every file below.
Source
// Local-first with barrel-lite: two clients keep a local copy of
// one database, edit offline, sync, and resolve a conflict.
import { Database, MemoryAdapter, SyncError } from "barrel-lite";
const URL = process.env.BARREL_URL ?? "http://localhost:8080";
const DB = "lf_groceries";
// A fetch we can switch off to simulate a lost connection.
let online = true;
const phoneFetch = (input: string, init?: RequestInit) =>
online ? fetch(input, init) : Promise.reject(new TypeError("offline"));
// Start from an empty database on the server (REST).
await fetch(`${URL}/db/${DB}?purge=true`, { method: "DELETE" });
await fetch(`${URL}/db/${DB}`, { method: "PUT" });
// In Node the local store is in memory; in a browser it is OPFS.
const phone = await Database.open(DB, {
remote: { url: URL, db: DB, fetch: phoneFetch },
storage: new MemoryAdapter(),
});
const laptop = await Database.open(DB, {
remote: { url: URL, db: DB },
storage: new MemoryAdapter(),
});
// 1. Local writes and reads need no server.
await phone.put({ id: "list", title: "Groceries", items: ["milk"] });
const local = await phone.get("list");
console.log("phone local get:", local?.["items"]);
// 2. Sync: push the phone's copy, pull it on the laptop.
const first = await phone.sync();
console.log("phone sync: pushed", first.push.pushed);
const pulled = await laptop.pull();
console.log("laptop pull: applied", pulled.applied);
console.log("laptop get:", (await laptop.get("list"))?.["items"]);
// 3. The phone goes offline and keeps working.
online = false;
await phone.put({ id: "list", title: "Groceries",
items: ["milk", "eggs"] });
await phone.put({ id: "note", text: "store closes at 20:00" });
try {
await phone.sync();
} catch (e) {
if (!(e instanceof SyncError)) throw e;
console.log("phone sync while offline:", e.code);
}
console.log("phone local docs:",
(await phone.allDocs()).map((d) => d.id).sort());
// Meanwhile the laptop edits the same document and syncs.
await laptop.put({ id: "list", title: "Groceries",
items: ["milk", "bread"] });
await laptop.push();
// 4. Back online: the phone's edits go up, the laptop's come down.
online = true;
const back = await phone.sync();
console.log("phone sync back online: pushed", back.push.pushed,
"applied", back.pull.applied);
const winner = await phone.get("list");
const others = await phone.conflicts("list");
console.log("phone list:", winner?.["items"]);
console.log("phone conflicts:", others.map((c) => c.body?.["items"]));
// 5. Resolve once: merge both edits, push the resolution.
const items = new Set<string>();
for (const body of [winner, ...others.map((c) => c.body)]) {
for (const i of (body?.["items"] as string[] | undefined) ?? []) {
items.add(i);
}
}
await phone.resolve("list", { title: "Groceries",
items: [...items].sort() });
await phone.push();
await laptop.pull();
console.log("laptop list:", (await laptop.get("list"))?.["items"]);
console.log("laptop conflicts:", (await laptop.conflicts("list")).length);
// 6. Local BQL over the synced copy, and the server's view.
const rows = await laptop.query(
"SELECT id, text FROM c WHERE text IS NOT NULL");
console.log("laptop query:", rows);
const res = await fetch(`${URL}/db/${DB}/doc/list`);
const server = (await res.json()) as { items: string[] };
console.log("server list:", server.items);
await phone.close();
await laptop.close(); {
"name": "barrel-local-first-example",
"private": true,
"type": "module",
"engines": { "node": ">=22.6" },
"scripts": {
"start": "node --experimental-strip-types main.ts",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^22.10.0",
"typescript": "^5.9.3"
}
} #!/bin/sh
# Type-check, then run main.ts against BARREL_URL
# (default http://localhost:8080). barrel-lite must be installed:
# npm install /path/to/barrel/clients/barrel-lite
set -e
cd "$(dirname "$0")"
[ -d node_modules/barrel-lite ] || {
echo "install barrel-lite first (see README)" >&2; exit 1; }
npx tsc --noEmit >&2
exec node --experimental-strip-types --no-warnings main.ts Expected output
The expected.txt of the example, from a real run. Revisions, ids, tokens and timestamps differ on every run; scripts/verify-examples.sh masks them before it compares.
phone local get: [ 'milk' ]
phone sync: pushed 1
laptop pull: applied 1
laptop get: [ 'milk' ]
phone sync while offline: network
phone local docs: [ 'list', 'note' ]
phone sync back online: pushed 2 applied 1
phone list: [ 'milk', 'bread' ]
phone conflicts: [ [ 'milk', 'eggs' ] ]
laptop list: [ 'bread', 'eggs', 'milk' ]
laptop conflicts: 0
laptop query: [ { id: 'note', text: 'store closes at 20:00' } ]
server list: [ 'bread', 'eggs', 'milk' ]