Quickstart: sync from any language over REST + WebSocket
Use Kovlet from any language, with no SDK. This guide is for languages without a Kovlet SDK (Python, Go, …), or for writing your own client.
On this page
What you'll build
- A small client that signs in with a short code the person approves in their browser.
- It finds or creates a Data Space over REST, using plain HTTP calls.
- It syncs a todos table and a file over one WebSocket.
- At the end, the whole thing as one runnable script with no dependencies, ready to port to your language.
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.
The API base is https://api.kovlet.com, or http://127.0.0.1:8080 for local development. The website and sign-in pages are https://kovlet.com.
Step 1: Sign in
Start a device codeA short code the app shows and the user approves at https://kovlet.com/activate. Codes expire after 10 minutes. sign-in (RFC 8628). The app gets a short code, and the person approves it in a browser.
client_nameis your app's name on the consent screen.space_namesuggests the name of a new space for a first-time user.
curl -s -X POST https://api.kovlet.com/v1/oauth/device_authorization \
-d client_name=Todos -d machine_name=laptop -d space_name=TodosThe answer has device_code, user_code, verification_uri_complete and interval.
Show the person verification_uri_complete. They sign in on https://kovlet.com, confirm the code and pick the spaces the app may use. Meanwhile, poll POST /v1/oauth/token every interval seconds:
curl -s -X POST https://api.kovlet.com/v1/oauth/token \
-d grant_type=urn:ietf:params:oauth:grant-type:device_code -d device_code=kvc_...The poll answers authorization_pending until the person approves. Then it answers {"access_token": "kvs_...", "expires_in", ...}.
Use that token everywhere:
- Send
Authorization: Bearer kvs_...on every REST call. - Put the same token in
hello.tokenon the socket.
This keyless token lasts 90 days and has no refresh. Two other options are in protocol §2:
- Stay signed in on a device. A native app that should stay signed in on the person's device adds
device_public_key(a P-256 JWK) to the device authorization. It then signs a device proof per request, which gives it a refresh token. - PKCE redirects for mobile and desktop apps work too.
Step 2: Pick or create a space
A Data SpaceA set of typed tables plus a tree of files, shared by every app with access to it. holds your tables and files. GET /v1/spaces lists the spaces this app may use:
curl -s https://api.kovlet.com/v1/spaces -H "Authorization: Bearer kvs_..."The answer is {"spaces": [{"id", "name", "slug", "role", ...}], "requestable", "can_create"}. It lists the spaces this app was granted. role is "" while an admin still has to approve the app.
POST /v1/spaces makes a new space. The person owns it, and this app gets the editor role:
curl -s -X POST https://api.kovlet.com/v1/spaces -H "Authorization: Bearer kvs_..." \
-H "Content-Type: application/json" -d '{"name": "Todos", "slug": "todos"}'- Send a
slug. Then a retry answers409 slug_takeninstead of making a second space. - To ask the person for one of their other spaces, call
POST /v1/grant-requests. It returns an approve link. See protocol §2.8.
Step 3: Sync a table
Rows and file metadata are written over a WebSocket. There is no REST call to write a row.
Open wss://api.kovlet.com/v1/sync (GET /v1/sync), one connection per space. Send hello within 10 seconds. Its schema declares your tables. A new table or optional column is created on connect.
{"type": "hello", "protocol": 1, "space_id": "<space id>", "since_seq": 0, "token": "kvs_...",
"schema": {"todos": {"columns": {"title": {"type": "string"}, "done": {"type": "boolean"}}, "order": ["title", "done"]}}}The server answers with snapshotThe full state of a Data Space, sent when a client connects with since_seq: 0. frames until one has complete: true. Together they are the whole space:
records: each hastable,id,fields,hlcsand, optionally,deleted.files.- Either list may be missing from a frame when it is empty.
Keep head_seq. Send it as since_seq when you reconnect, so you only get a delta (the changes since then).
Write with mutate, at most 500 mutations per frame:
{"type": "mutate", "space_id": "<space id>", "mutations": [
{"mutation_id": "<uuid>", "hlc": "1764314700123:00000:my-device", "kind": "record", "op": "upsert",
"table": "todos", "id": "<row id>", "fields": {"title": "Buy milk", "done": false}}]}ackanswers each mutation in order:applied,duplicate(treat it like applied) orrejectedwith anerrorthat has ahint.- Changes from other apps arrive as
broadcastframes. - Fields merge last-writer-winsThe merge rule for each field: the write with the higher HLC stamp wins. per field, ordered by
hlc. hlcis a clock stamp,wall_ms:counter:node_id, with a 5-digit counter from00000to65535. Keep it increasing per client.mutation_idmakes a resend after a reconnect safe.- Record ops are
upsert,deleteandrestore.
Step 4: FilesOptional
Uploading a file takes three steps:
POST /v1/spaces/{space}/files/uploadswith{"sha256", "size_bytes", "mime_type"}.- Unless the answer says
exists: true, send the bytes toupload.urlwithupload.methodand every header inupload.headers. - Commit the file with a
filemutation (a fileput):{"kind": "file", "op": "put", "id": "<file id>", "file": {"path", "sha256", "size_bytes", "mime_type"}}.
To write a new version of an existing path, reuse that file's id from the snapshot. A new id on a taken path is rejected with path_conflict.
To download, call GET /v1/spaces/{space}/files/{id}/download. It returns a short-lived URL.
The whole thing in one script
Here is every step above, in one runnable file. It needs Node 22 or newer for the global fetch and WebSocket, and nothing from npm. Port it line by line to Python, Go, Rust, Swift or Kotlin.
// todos.mjs: Kovlet over plain REST + WebSocket, no SDK. Node 22+, no dependencies.
const API = process.env.KOVLET_URL ?? "https://api.kovlet.com";
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const form = (body) => ({
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(body),
});
// 1. Sign in: device code flow. The user approves once in the browser.
const da = await (
await fetch(
`${API}/v1/oauth/device_authorization`,
form({ client_name: "Todos", machine_name: "laptop", space_name: "Todos" }),
)
).json();
console.log(`Open ${da.verification_uri_complete} and confirm ${da.user_code}`);
let token;
while (!token) {
await sleep(da.interval * 1000);
const t = await (
await fetch(
`${API}/v1/oauth/token`,
form({ grant_type: "urn:ietf:params:oauth:grant-type:device_code", device_code: da.device_code }),
)
).json();
if (t.access_token) token = t.access_token;
else if (t.error !== "authorization_pending" && t.error !== "slow_down")
throw new Error(t.error_description ?? t.error);
}
const auth = { Authorization: `Bearer ${token}` };
// 2. Pick or create a space: the ones this app may use, or a new one.
const list = await (await fetch(`${API}/v1/spaces`, { headers: auth })).json();
let space = list.spaces.find((s) => s.name === "Todos" && s.role === "editor");
if (!space) {
const res = await fetch(`${API}/v1/spaces`, {
method: "POST",
headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({ name: "Todos", slug: "todos" }),
});
space = (await res.json()).space;
}
// 3. Sync a table over the WebSocket.
let wall = 0;
let counter = 0;
const hlc = () => {
const now = Date.now();
if (now > wall) [wall, counter] = [now, 0];
else if (++counter > 65535) [wall, counter] = [wall + 1, 0];
return `${wall}:${String(counter).padStart(5, "0")}:todos-cli`;
};
const rows = new Map();
const files = new Map(); // path -> file id
const ws = new WebSocket(`${API.replace(/^http/, "ws")}/v1/sync`);
const frames = [];
let wake = () => {};
ws.onmessage = (e) => {
frames.push(JSON.parse(e.data));
wake();
};
const next = async (type) => {
for (;;) {
const i = frames.findIndex((f) => f.type === type || f.type === "error");
if (i >= 0) {
const [f] = frames.splice(i, 1);
if (f.type === "error") throw new Error(`${f.code}: ${f.message} (${f.hint ?? ""})`);
return f;
}
await new Promise((r) => (wake = r));
}
};
await new Promise((r) => (ws.onopen = r));
ws.send(
JSON.stringify({
type: "hello",
protocol: 1,
space_id: space.id,
since_seq: 0,
token,
schema: { todos: { columns: { title: { type: "string" }, done: { type: "boolean" } }, order: ["title", "done"] } },
}),
);
for (let snap = await next("snapshot"); ; snap = await next("snapshot")) {
for (const r of snap.records ?? []) if (r.table === "todos" && !r.deleted) rows.set(r.id, r.fields);
for (const f of snap.files ?? []) if (!f.deleted) files.set(f.path, f.id);
if (snap.complete) break;
}
const id = crypto.randomUUID();
ws.send(
JSON.stringify({
type: "mutate",
space_id: space.id,
mutations: [
{
mutation_id: crypto.randomUUID(),
hlc: hlc(),
kind: "record",
op: "upsert",
table: "todos",
id,
fields: { title: process.argv[2] ?? "Buy milk", done: false },
},
],
}),
);
const ack = await next("ack");
console.log(ack.results[0].status, `- ${rows.size + 1} todos in space ${space.name}`);
// 4. Files: upload the bytes, then commit the file with a mutation.
const bytes = new TextEncoder().encode("Shopping list\n");
const sha256 = Buffer.from(await crypto.subtle.digest("SHA-256", bytes)).toString("hex");
const up = await (
await fetch(`${API}/v1/spaces/${space.id}/files/uploads`, {
method: "POST",
headers: { ...auth, "Content-Type": "application/json" },
body: JSON.stringify({ sha256, size_bytes: bytes.length, mime_type: "text/plain" }),
})
).json();
if (!up.exists) await fetch(up.upload.url, { method: up.upload.method, headers: up.upload.headers, body: bytes });
ws.send(
JSON.stringify({
type: "mutate",
space_id: space.id,
mutations: [
{
mutation_id: crypto.randomUUID(),
hlc: hlc(),
kind: "file",
op: "put",
id: files.get("notes/list.txt") ?? crypto.randomUUID(),
file: { path: "notes/list.txt", sha256, size_bytes: bytes.length, mime_type: "text/plain" },
},
],
}),
);
console.log("file", (await next("ack")).results[0].status);
ws.close();Run it against the hosted API, or against a local server with KOVLET_URL:
node todos.mjs "Walk the dog"
KOVLET_URL=http://127.0.0.1:8080 node todos.mjs # against a local kovletd --devOn the first run it prints this (your code differs):
Open https://kovlet.com/activate?user_code=9DND-HFZF and confirm 9DND-HFZF
applied - 1 todos in space Todos
file appliedYou should see
- First, the
Open … and confirm …line with a link and a code. The script waits until you approve the code. - Then
applied - 1 todos in space Todos. The count includes rows other apps already wrote to the space, so it grows with each run. - Last,
file applied.
A real client also keeps the socket open. It:
- applies
broadcastframes as they arrive, - queues writes while offline and resends them with the same
mutation_id, - reconnects with
since_seq.
Protocol §3 and the client checklist list the rules.
The API in brief
- API base:
https://api.kovlet.com(local dev:http://127.0.0.1:8080). The website and sign-in pages arehttps://kovlet.com. - Sign in:
POST /v1/oauth/device_authorization, the person approves, then pollPOST /v1/oauth/token. - Spaces:
GET /v1/spaceslists what this app may use, andPOST /v1/spacescreates one. - Rows and file metadata are written over the WebSocket (
GET /v1/sync):hello, thenmutate, then read theack. There is no REST row write. - Files:
POST .../files/uploads, PUT the bytes, then a fileputmutation.
The protocol reference is the normative contract.
- JSON Schemas for every frame are at /protocol/schema.
- Every REST route is in /openapi.json.
- Protocol §14 is the client checklist. Its conformance suite (
kovletd conformance) drives a client through the same rules against a fake server.
Local development
kovletd --dev --dev-auto-approve approves every device code at once as the dev user, so a test run needs no browser. Use http://127.0.0.1:8080 as the API base. Run Kovlet locally starts kovletd --dev with Docker or the kovletd binary.
Next
- Share live data between two AI-built apps: the tutorial that connects a second app to the same Data Space.
- Kovlet sync protocol reference: every frame, merge rule and error.
- Let strangers sign in to your app (end users): public apps with their own users.
- /llms-full.txt: the full reference.
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.