Connect your own frontend
Wire a web app you build yourself to your Oalo Base: sign members in with an email code, then sync their data with @synclib-io/client.
Use this page when you build a web app yourself, on your own machine, and want your Oalo Base to be its backend: members sign in with an email code, and their data syncs to a local database in the browser.
If you would rather start from working code, the apps Oalo creates already have
all of this wired. oalo apps lists them, and oalo deploy --app <slug> --pull
fetches one's code as the git branch oalo/<slug>.
What you need
- Your Base URL,
https://<slug>.oalo.ai. Everything below is on it. - Your app's slug (
oalo appslists it) and an env,devorprod. The env picks which copy of the data the app reads and writes. Usedevwhile building. - No token in the app. The app gets each member's token by signing them in. Never put a Sync API token, a Bot API token or a CLI token in a web or mobile app: those act as the whole workspace and expose every member's rows. See Tokens and credentials.
You can call the Base directly from http://localhost. The auth endpoints
allow any origin, and the sync socket accepts connections from any origin, so a
dev proxy is optional.
GET /api/_platform/routes on your Base lists the auth, commerce and checkout
endpoints with their request bodies. It needs no token.
1. Install
npm i @synclib-io/client
The browser database needs three static files served from one folder of your
app. Copy them into public/:
cp node_modules/sql.js/dist/sql-wasm.wasm public/
cp node_modules/@synclib-io/core/wasm/synclib_hash.js node_modules/@synclib-io/core/wasm/synclib_hash.wasm public/
The client finds synclib_hash.js next to sql-wasm.wasm, so keep them
together.
Tables come from your Base's data models (oalo data models lists them). For
data each member keeps to themselves, make the model per-member:
oalo data models create notes --field title --field body:text --owned-by user_id.
Without --owned-by, every member sees every row.
For typed rows, run oalo typegen in the project. It writes
oalo.generated.ts with a type per table and a MODELS object that says
which tables are shared and which are owned by a member.
2. Sign members in
All four endpoints take and return JSON. A missing field answers 400. A wrong
or expired code on verify-code, or a refresh token that no longer works,
answers 401. Both come with {"error": "<message>"}.
| Call | Body | Returns |
|---|---|---|
POST /api/auth/request-code | {email} | Emails a 6-digit code. It expires in 10 minutes. At most 3 codes per email, and 20 per client address, per 10 minutes. |
POST /api/auth/verify-code | {email, code} | {token, refresh_token, user}. Five wrong codes lock the email out for 10 minutes. |
POST /api/auth/refresh-token | {refresh_token} | {token, refresh_token, user} |
POST /api/auth/logout | {token} | Ends the session: the token and its refresh token stop working. |
user is {id, email, username, avatar_url, has_pro, purchased_products, language}. user.id is the member's id: you need it for the channel in step 3.
tokenis the access token (a signed JWT). It lasts 1 hour. Send it to the sync client, and asAuthorization: Bearer <token>to the endpoints that take one.refresh_tokenlasts 30 days from its last use. Each refresh returns a new one: store it every time, replacing the old one.- Refresh ahead of expiry, for example every 45 minutes, so the live socket never reconnects with an expired token.
- You never create or sign tokens yourself. The Base issues them.
has_proandpurchased_productssay what the member has paid for. Gate paid content on them. See Commerce.
const BASE = "https://<slug>.oalo.ai";
async function post(path: string, body: object) {
const res = await fetch(BASE + path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (!res.ok) throw new Error((await res.json().catch(() => ({}))).error || `HTTP ${res.status}`);
return res.json();
}
await post("/api/auth/request-code", { email });
const { token, refresh_token, user } = await post("/api/auth/verify-code", { email, code });
// Keep all three. On refresh, replace token AND refresh_token.
3. Connect sync
Every table goes on one channel whose topic is exactly
sync:app:app_builder. It is a fixed name, the same in every app. A
signed-in member also joins sync:user:<user.id> with no tables: live
changes to a member's own rows arrive there, so it is a listener only.
import { SynclibClient, SynclibStore } from "@synclib-io/client";
import { MODELS } from "./oalo.generated";
const SLUG = "<slug>";
const ENV = "dev"; // or "prod"
const tables = Object.keys(MODELS).map((name) => ({ name }));
const userId: string | null = user?.id ?? null; // null when signed out
const store = await SynclibStore.create({
// One database per person, so the next person on this device never sees
// the previous one's rows.
databaseName: `app_${SLUG}_${ENV}_${userId ?? "anon"}`,
wasmUrl: "/sql-wasm.wasm",
});
const client = new SynclibClient({
serverUrl: BASE.replace(/^http/, "ws") + "/socket",
channels: [
{
topic: "sync:app:app_builder",
role: userId ? "bidirectional" : "pull",
tables,
},
...(userId ? [{ topic: `sync:user:${userId}`, role: "pull" as const, tables: [] }] : []),
],
clientId: `app_${SLUG}_${userId ?? "anon"}`,
connectParams: { slug: SLUG, env: ENV },
// Signed out, the app connects as itself: shared rows only, read-only.
getToken: async () => (userId ? currentAccessToken() : `app_builder:${SLUG}`),
merkleVerifyInterval: 24 * 60 * 60 * 1000,
});
// connect() pulls only tables this device has never had. Pull the rest
// once the client is ready, on this connect and on every later one.
client.onSyncReadyStateChange((state) => {
if (state === "ready") client.syncUnified().catch(() => {});
});
await client.initialize(store);
await client.connect();
The Base sends the table definitions when the client connects, so you never create tables yourself.
Four things the client does not do for you:
-
After connecting, pull.
connect()joins the channels and pulls a table only the first time the device sees it. A returning visitor gets nothing that changed while they were away until something callssyncUnified(). TheonSyncReadyStateChangelistener above does that. -
After a reconnect, call
client.syncUnified()whenonConnectionStateChangereports"connected"again. Otherwise writes made while offline wait for the next write. -
After a token refresh, call
client.updateToken(newToken), so the next reconnect and the HTTP fallback use the new one. -
When the socket can't be held, the client switches to HTTP. Poll
syncUnified()whileonTransportChangereportsmode: "http". See Sync HTTP fallback.
When the person changes (sign-in, sign-out, a different member):
disconnect(), store.close(), then build a new store and client for the new
person. Delete the previous person's local database (it lives in the browser's
IndexedDB database synclib_databases, store databases, keyed by
databaseName).
4. Read and write rows
Reads and writes go to the local database. The client syncs them.
Every table has these columns: id, document (the fields, as JSON text),
owner_id, availability, product_id, last_modified_ms, deleted_at.
Deleted rows stay with deleted_at set, so filter them out.
// Read
const rows = await store.query(
"SELECT * FROM notes WHERE deleted_at IS NULL ORDER BY last_modified_ms DESC LIMIT 50", []);
const notes = rows.map((r) => ({ id: r.id, ...JSON.parse(r.document) }));
// A document field in a query
await store.query("SELECT * FROM notes WHERE json_extract(document, '$.pinned') = 1 AND deleted_at IS NULL", []);
Write with store.write, not store.query. write records the change so the
client pushes it. It takes the SQL for the local database and, as data, the
row as the Base should receive it:
// Insert
const id = crypto.randomUUID();
const now = Date.now();
const doc = { title: "Hi", pinned: false, _id: id };
await store.write({
tableName: "notes", rowId: id, operation: "insert",
sql: "INSERT INTO notes (id, document, owner_id, availability, product_id, last_modified_ms) VALUES (?, ?, ?, ?, ?, ?)",
params: [id, JSON.stringify(doc), null, "free", null, now],
data: JSON.stringify({ document: doc, owner_id: null, availability: "free", product_id: null, last_modified_ms: now }),
});
// Update: read the row, merge, and send the whole document plus the row's
// availability and product_id. A field set to null is removed.
const [row] = await store.query("SELECT document, availability, product_id FROM notes WHERE id = ? AND deleted_at IS NULL", [id]);
const merged = { ...JSON.parse(row.document), title: "Renamed" };
const at = Date.now();
await store.write({
tableName: "notes", rowId: id, operation: "update",
sql: "UPDATE notes SET document = ?, availability = ?, product_id = ?, last_modified_ms = ? WHERE id = ?",
params: [JSON.stringify(merged), row.availability, row.product_id, at, id],
data: JSON.stringify({ document: merged, availability: row.availability, product_id: row.product_id, last_modified_ms: at }),
});
// Delete (soft)
await store.write({
tableName: "notes", rowId: id, operation: "delete",
sql: "UPDATE notes SET deleted_at = ?, last_modified_ms = ? WHERE id = ?",
params: [Date.now(), Date.now(), id],
data: JSON.stringify({ deleted_at: Date.now(), last_modified_ms: Date.now() }),
});
What the Base allows:
- Signed out: shared rows only, and no writes.
- A signed-in member: shared rows plus their own rows of owned tables.
They can create rows, and change or delete only their own. The Base sets
owner_idto the member on insert, whatever the app sends, so leave itnull.
To re-render when data changes (a local write, a push from the Base, a catch-up after reconnect):
const off = client.onTableChange("notes", () => reloadNotes());
In React, @synclib-io/react gives you SynclibProvider,
useSynclibClient() and useSynclibStore(), so components can reach the
client and store. Subscribe with onTableChange in an effect.
5. Sell content and unlock it after a purchase
A row with availability premium or product comes down stripped until
the member has paid: only its preview fields, plus document._stripped: true.
Show a paywall when you see _stripped. A draft row never reaches members or signed-out visitors.
See Commerce.
Send the buyer to the Base's hosted checkout:
const params = new URLSearchParams({
productId: "premium", // the product's id
return_url: location.href, // where Continue goes after paying
prefilledEmail: user.email,
});
location.href = `${BASE}/checkout?${params}#token=${encodeURIComponent(token)}`;
return_urlis where the buyer goes back to. After paying, the success screen shows Continue, which opens it withpurchase=successadded to its query. (returnUrlalso works.)#token=is the member's access token, in the fragment so it never reaches a server log. With it, the order is the member's. Without it, the order is matched to a member by the email typed at checkout.
Nothing re-syncs by itself after a purchase. When the page opens with
?purchase=success:
// 1. A fresh token: its purchased_products now include the product.
const next = await post("/api/auth/refresh-token", { refresh_token });
saveTokens(next); // store token AND refresh_token
client.updateToken(next.token);
// 2. Forget the tables' sync position, reconnect with the new token, pull.
client.nullOutSeqnums(tables.map((t) => t.name));
await client.disconnect();
await client.connect(); // the "ready" listener from step 3 runs syncUnified()
The stripped rows then come down in full. If they're still stripped, check
that purchased_products in the refreshed user has the product: the order
may be linked to a different email.
Common mistakes
- A Sync API token in the app. It reads and writes every member's rows. Sign members in instead.
- Another topic name. The shared channel is always
sync:app:app_builder. A made-up topic (sync:app:<my app>) joins, but live changes to shared rows are only sent onsync:app:app_builder, so the app never sees them. - Only joining
sync:user:<id>. Live changes to shared rows are sent onsync:app:app_builder, so an app that isn't on that channel sees them only on its next sync. Put the tables on the shared channel, as above. - Writing with
store.query. The row changes locally and never reaches the Base. Usestore.write. - Keeping the old refresh token. After a refresh only the new one works.
- Expecting a reconnect to pull.
connect()doesn't pull tables the device already has. CallsyncUnified()when the client is ready, as in step 3, or a purchase (or anything changed while away) never shows up. - One database for everyone on the device. Name it per person, as above.
How people sign in to your app, and how Oalo proves who they are.
The mental model behind Oalo's offline-first data sync, its core concepts, and how the TypeScript and Dart client libraries are layered.
The consumer-facing TypeScript and Dart client API for wiring Oalo sync into your app.
The six kinds of credential in Oalo, what each one is for, how to create it, and which ones are safe to put in an app.
How to define your own data tables in Oalo, import a CSV, stage and promote data, and push data in from another system through the Data API.
How the sync client keeps reading and writing over HTTP when the WebSocket drops, and what you must poll while degraded.
Sign up, install the CLI, and deploy your repo in a few minutes.