Quickstart: sync your own database from Node, Electron or React Native
Keep your data in your own SQLite database, or any other store, and let Kovlet keep it in sync. You won't need an API key: the person running the app approves it once with a short code.
On this page
What you'll build
- A Node script that adds a todo to your own
todos.dband syncs it to a Kovlet Data Space. - Changes from every other app on the same space land in your database, ready for plain SQL.
- Sign-in with a short code the person approves in their browser, once.
- You'll need Node 22 or newer and a free Kovlet account, or Kovlet running on your machine.
Prerequisites
You need a Kovlet server. Pick one:
- The hosted API at
https://api.kovlet.com. The free plan is enough for testing. You sign in on the console athttps://kovlet.com. - A local
kovletd --dev, from theghcr.io/kovlethq/kovletdDocker image or thekovletdbinary. Run Kovlet locally starts it and shows how to approve your app from the terminal.
Step 1: Install
npm i @kovlet/clientYou need Node 22 or newer, because the client uses the built-in fetch and WebSocket. Use ESM ("type": "module") so you can use top-level await.
Step 2: Declare the space, your store and sign in
Create kovlet.ts. It opens your database, names your app, lists the tables it syncs, and tells Kovlet how to write incoming changes into your database.
import { DatabaseSync } from "node:sqlite"; // or better-sqlite3
import { createKovletClient, t } from "@kovlet/client";
import { SqliteStore } from "@kovlet/client/sqlite";
const db = new DatabaseSync("todos.db");
db.exec("CREATE TABLE IF NOT EXISTS todos (id TEXT PRIMARY KEY, title TEXT, done INTEGER, trashed INTEGER)");
const get = db.prepare("SELECT title, done FROM todos WHERE id = ?");
const put = db.prepare("INSERT OR REPLACE INTO todos VALUES (?, ?, ?, ?)");
export const kovlet = createKovletClient({
appName: "Todos",
spaces: {
main: { files: true, tables: { todos: { title: t.string(), done: t.boolean() } } },
},
store: new SqliteStore(db, {
// Changes arrive merged: a field patch for "upsert", the trash flag for "delete"/"restore".
apply: (_db, c) => {
if (c.kind === "upsert") {
const row = { ...(get.get(c.id) as object | undefined), ...c.fields } as { title?: string; done?: unknown };
put.run(c.id, row.title ?? null, row.done ? 1 : 0, c.deleted ? 1 : 0);
} else if (c.kind === "delete" || c.kind === "restore") {
db.prepare("UPDATE todos SET trashed = ? WHERE id = ?").run(c.kind === "delete" ? 1 : 0, c.id);
} else if (c.kind === "purge") {
db.prepare("DELETE FROM todos WHERE id = ?").run(c.id);
}
},
}),
});- Line 11
appNameis what the person sees when they approve your app, and in the console. - Line 13
mainis a slotA named placeholder for a Data Space, filled in when someone approves the app.. It stands for one Data Space. The person picks which of their spaces fills it, or a new one is created. - Line 15
SqliteStorecomes from@kovlet/client/sqlite. It keeps Kovlet's bookkeeping in the same SQLite database as your rows. - Lines 17–26your
applyfunction receives each change after the client has merged it against its own clocks. You only get the fields that won. The client callsapplyin the same transaction as its own bookkeeping. Anupsertchange carries a patch of fields,deleteandrestoreset the trash flag, andpurgeremoves the row for good.
The API base defaults to https://api.kovlet.com. Against a local kovletd --dev, pass url: "http://127.0.0.1:8080" and consoleUrl: "http://localhost:5173". Run Kovlet locally starts both with one Docker command.
How sign-in works
In Node, sign-in defaults to a device codeA short code the app shows and the user approves at https://kovlet.com/activate. Codes expire after 10 minutes.. On first connect, the client prints [kovlet] To connect Todos, open <url> and confirm code <code>.
The person signs in on https://kovlet.com, confirms the code and approves the app. Usually they keep the suggested new space named after the app.
- To show the code in your own UI, pass
auth: { type: "device", onCode }. - The session is bound to this device and refreshes itself.
- The session is kept in memory unless you pass a persistent
storage. Without it, a script that restarts asks again. - Your rows, the outboxThe client's queue of local writes not yet acknowledged by the server. and the sync cursor persist in
todos.db. A restart only catches up on what changed.
Other ways to sign in:
auth: { type: "pkce", redirectUri, authorize }for an Electron or React Native consent window.{ type: "machine-key", machineKey, clientId }for unattended servers. PinspaceIdon each slot, because a machine key can't pick a space.
Step 3: Pick or create a spaceOptional
Right after the person approves, each slot without a spaceId gets its space. So connect() resolves with every slot mapped. By default the client chooses, in this order:
- The space named after the app (what
/activatesuggests). - Otherwise, the only space shared with the app.
- Otherwise, a new space it creates.
- Otherwise, an approve link asking the person for one.
This works even for a person with no spaces at all. To decide yourself, for example by asking the person, pass pickSpace:
import { createKovletClient, t } from "@kovlet/client";
export const kovlet = createKovletClient({
appName: "Todos",
spaces: { main: { tables: { todos: { title: t.string(), done: t.boolean() } } } },
auth: {
type: "device",
// ctx: slot, role, spaces (usable here), canCreate, requestable, suggestedName
pickSpace: (ctx) => {
const existing = ctx.spaces.find((s) => s.name === "Todos");
return existing ? { spaceId: existing.id } : { create: { name: ctx.suggestedName } }; // or { request: true }
},
},
});- The pick is stored with the session, so later runs don't pick again.
- Say there are several possible spaces and none is named after the app. Then the default fails with
space_choice_required, and you needpickSpace. - A pinned
spaceIdskips all of this. - A client may also declare no slots (
spaces: {}) and only manage spaces.
Once signed in, the app can manage more spaces itself, without the console:
import { kovlet } from "./kovlet";
await kovlet.connect(); // signs in (or reuses the session) first
const { spaces, can_create } = await kovlet.listSpaces();
console.log(spaces.map((s) => `${s.name} (${s.role || s.reason})`));
if (can_create && !spaces.some((s) => s.name === "Archive")) {
await kovlet.createSpace({ name: "Archive", slug: "archive" }); // this app gets editor
}
kovlet.disconnect(); // let a script exitcreateSpace also takes slot. That is the name of a slot you declared in spaces (here only main), and it then syncs the new space. An undeclared slot name maps nothing. To ask the person for another existing space, call kovlet.requestSpaces({ asks: [...], onLink }). It sends them an approve link, without a new sign-in.
Step 4: Sync a table
import { kovlet } from "./kovlet";
await kovlet.connect(); // first run: prints the link and code, and resolves once the user approves
const todos = kovlet.space("main").table("todos");
await todos.insert({ title: process.argv[2] ?? "Buy milk", done: false }); // written to todos.db, then synced
await kovlet.whenSynced(); // resolves once the server has acknowledged every write (30 s timeout)
kovlet.disconnect(); // let a script exit; a long-running app keeps syncing insteadWrite with kovlet.space(slot).table(name) and its insert, update and delete. In this mode they return promises. Read from your own database.
Run it with npx tsx main.ts "Buy milk". On the first run, it prints a link and a code (your code differs):
[kovlet] To connect Todos, open https://kovlet.com/activate?user_code=FHXJ-TFMW and confirm code FHXJ-TFMWApprove the code in the browser. The script exits once the server has acknowledged the row. Node 22 may also print an ExperimentalWarning for node:sqlite. Then look for the row in your own database:
sqlite3 todos.db "SELECT title, done FROM todos"Buy milk|0You should see
- On the first run, the
[kovlet] To connect Todosline with a link and a code. - After you approve, the script exits on its own.
- The new row,
Buy milk|0, intodos.db.
Changes from every other app on the space land in todos.db through apply. Read them with plain SQL.
Two more options:
- Record mode. If you write your own rows in your own transaction, call
table.record(id, fields)inside it instead. - Any other store. Pass
store: { dataStore, syncStore }. ThedataStorehas one method,apply(batch).
Step 5: FilesOptional
Declare files: true on the slot. File metadata reaches your apply as file changes (c.kind === "file"). The bytes come on demand, by file id:
import { writeFile } from "node:fs/promises";
import { kovlet } from "./kovlet";
export async function save(fileId: string, to: string) {
const { bytes, mimeType } = await kovlet.space("main").files.download(fileId); // sha256-verified
await writeFile(to, bytes);
return mimeType;
}files.url(id)returns a short-lived download URL.- In headless mode (with a
store), the client does not upload yet. Upload with the three REST steps in the REST quickstart. - Or create the client without
store. Thenspace.files.upload()works in Node as in the browser.
Electron and React Native
- Electron: run the client in the main process with
SqliteStore. Sign in withauth: { type: "pkce", redirectUri, authorize }in aBrowserWindow, or keep the device code. - React Native: pass a
{ dataStore, syncStore }pair over your storage. Usepkcewith the system browser and acom.example.todos:/kovlet/callbackredirect. - Tauri: use the Rust plugin instead: Tauri quickstart.
Next
- Share live data between two AI-built apps: the tutorial that connects a second app to the same Data Space.
- /llms-full.txt: the full SDK reference (errors, schema evolution, quotas).
- Web and React and the native quickstarts sync the same space.
Ready to try it? Start free. No credit card, no API keys.
For coding agents: this page is also Markdown. Add .md to the URL or send Accept: text/markdown. The full reference is at /llms-full.txt.