Quickstart: sync a Rust or Tauri app with Kovlet
Add live sync that works offline to a Rust program or a Tauri 2 desktop app. People sign in once in the browser, and your SQLite tables stay in sync with every other app on the same Data Space.
On this page
What you'll build
- A Tauri or plain Rust todo app whose SQLite tables sync with every other app on the same Data Space.
- Sign-in once in the system browser. The app then finds or creates its space on its own.
- Writes land in your database at once and sync in the background, offline too.
- Optional extras: files, live queries, all-or-nothing writes, and sign-in for people without a Kovlet account.
You'll use two crates. kovlet is the client: it signs in, keeps the session fresh and syncs each Data Space over one WebSocket. tauri-plugin-kovlet adds browser sign-in, status events and pause/resume to a Tauri app.
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
Add the kovlet crate from crates.io. In a Tauri app, add tauri-plugin-kovlet too:
[dependencies]
kovlet = { version = "0.1", features = ["bundled-sqlite"] }
tauri-plugin-kovlet = "0.1" # Tauri apps onlybundled-sqlite compiles SQLite into the app. That way your database and Kovlet's bookkeeping share one SQLite build.
Requirements:
- Rust 1.85 or newer.
- For Tauri, its usual system libraries (webkit2gtk 4.1 on Linux).
- On Linux, the default OS keychain support needs
libdbus-1.
The client talks to https://api.kovlet.com by default (kovlet::DEFAULT_API_URL). Sign-in and consent pages open on the console, https://kovlet.com (kovlet::DEFAULT_CONSOLE_URL).
Step 2: Sign in
Tauri
Register the plugin. It builds one managed kovlet::Client, reachable from Rust as app.kovlet(). Its data lives under <app data dir>/kovlet.
use tauri_plugin_kovlet::KovletExt;
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_kovlet::init("Todos"))
.invoke_handler(tauri::generate_handler![open_space])
.run(tauri::generate_context!())
.expect("error while running app");
}Allow the plugin's commands in src-tauri/capabilities/default.json with "permissions": ["core:default", "kovlet:default"]. Then sign in from the webview:
const { invoke } = window.__TAURI__.core;
window.__TAURI__.event.listen("kovlet://status", ({ payload }) => showStatus(payload));
await invoke("plugin:kovlet|sign_in"); // PKCE in the system browser; or { flow: "device" }
await invoke("open_space"); // your command, belowBy default, sign-in uses PKCE, the standard browser sign-in for apps. It opens the system browser. The redirect comes back to a one-shot listener on your machine (http://127.0.0.1:<port>/callback).
Mobile (and custom schemes)
A phone can't run that local listener. So the consent page redirects to a deep link instead. Register two plugins, and hand each opened URL to the Kovlet plugin:
tauri-plugin-opener, the plugin's default opener. It's required on mobile.tauri-plugin-deep-link.
// Cargo: tauri-plugin-kovlet, tauri-plugin-deep-link = "2", tauri-plugin-opener = "2"
use tauri_plugin_deep_link::DeepLinkExt;
use tauri_plugin_kovlet::{KovletExt, Redirect};
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init()) // opens the consent page
.plugin(tauri_plugin_deep_link::init()) // brings the redirect back
.plugin(
tauri_plugin_kovlet::Builder::new("Todos")
.redirect(Redirect::DeepLink("com.example.todos:/kovlet/callback".into()))
.build(),
)
.setup(|app| {
let handle = app.handle().clone();
app.deep_link().on_open_url(move |e| {
for url in e.urls() {
handle.kovlet_handle_url(url.as_str()); // true when it finished a pending sign-in
}
});
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running app");
}
// tauri.conf.json: "plugins": { "deep-link": { "mobile": [{ "scheme": ["com.example.todos"], "appLink": false }] } }To open URLs some other way, set .open_url_with(|app, url| …) on the builder.
Add a space later, without signing in again
A phone that signed in with the device flow only reaches the spaces it was granted. To ask for more, call invoke("plugin:kovlet|spaces_request_access", { asks: [{ role: "editor" }] }). It:
- opens an approval page where the person picks (or creates) more spaces,
- emits that page's URL as
kovlet://approve-url, - resolves with
{ status, spaces }once they decide.
From Rust, call tauri_plugin_kovlet::request_access(&app, asks).
Plain Rust (CLI, server, other desktop toolkits)
use kovlet::{Client, SignIn};
let kovlet = Client::builder("Todos").data_dir(&dir).build()?;
if !kovlet.signed_in() {
kovlet.sign_in(SignIn::device(|c| println!("Open {} and enter {}", c.verification_uri, c.user_code))).await?;
}This uses a device codeA short code the app shows and the user approves at https://kovlet.com/activate. Codes expire after 10 minutes.: the app prints a link and a short code, and the person approves it in a browser. Two other flows:
SignIn::pkce(redirect_uri, authorize)is the browser flow, for apps that can open one.SignIn::machine_key(key, client_id)is for unattended servers.
Sign in once. The app stays signed in across restarts.
- The session refreshes itself. It is bound to a P-256 device keyA key pair the app creates and can't export. It binds a session to one device., so signing in again keeps the same machine.
- Tokens live in the OS keychain (macOS Keychain, Windows Credential Manager, Linux Secret Service). Where there is none, they live in 0600 files under
data_dir. - Check
signed_in()before callingsign_in.
Step 3: 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. This line finds the space named "Todos", or creates it:
let space_id = kovlet.spaces().find_or_create("Todos").await?.id;spaces().list()returns the spaces the person granted this app, plusrequestableandcan_create.spaces().create("Todos", Some("todos"))makes a new one. PassNonefor no slug.- Neither needs the console or another sign-in.
- Offline,
list()andfind_or_createreturn the last list the client saw (offline: true).
Step 4: Sync a table
Declare the tables, then open the space. The quickest path is the built-in store:
use kovlet::{col, Tables};
let tables = Tables::new().table("todos", [("title", col::string()), ("done", col::boolean())]);
let space = kovlet.open_builtin(&space_id, tables)?;
space.write("todos").upsert("t1", kovlet::serde_json::json!({ "title": "Buy milk", "done": false }))?;
let rows = space.table("todos").all()?; // or .observe(|rows| …)Want your own SQLite database to be the source of truth? Use SqliteStore::shared. Your apply function maps each merged change into your tables. It runs in the same transaction as Kovlet's bookkeeping:
use std::sync::{Arc, Mutex};
use kovlet::sqlite::rusqlite::{params, Connection};
use kovlet::{col, Change, Tables};
use tauri::Manager;
use tauri_plugin_kovlet::KovletExt;
/// Your app's state: its SQLite connection, shared with Kovlet, and the open space.
struct AppState {
db: Arc<Mutex<Connection>>,
space: Mutex<Option<kovlet::Space>>,
}
fn apply(tx: &Connection, _: &kovlet::ChangeBatch, change: &Change) -> kovlet::Result<()> {
match change {
Change::Upsert { table, id, fields, deleted } if table == "todos" => tx.execute(
"INSERT INTO todos (id, title, done, deleted) VALUES (?1, coalesce(?2, ''), coalesce(?3, 0), ?4)
ON CONFLICT(id) DO UPDATE SET title = coalesce(?2, title), done = coalesce(?3, done), deleted = ?4",
params![id, fields.get("title").and_then(|v| v.as_str()), fields.get("done").and_then(|v| v.as_bool()), deleted],
),
Change::Delete { table, id } if table == "todos" => tx.execute("UPDATE todos SET deleted = 1 WHERE id = ?1", [id]),
Change::Restore { table, id } if table == "todos" => tx.execute("UPDATE todos SET deleted = 0 WHERE id = ?1", [id]),
Change::Purge { table, id } if table == "todos" => tx.execute("DELETE FROM todos WHERE id = ?1", [id]),
_ => Ok(0),
}?;
Ok(())
}
#[tauri::command]
async fn open_space(app: tauri::AppHandle, st: tauri::State<'_, AppState>) -> Result<(), kovlet::Error> {
let id = app.kovlet().spaces().find_or_create("Todos").await?.id;
let store = kovlet::sqlite::SqliteStore::shared(st.db.clone(), apply)?; // Arc<Mutex<Connection>>
let tables = Tables::new().table("todos", [("title", col::string()), ("done", col::boolean())]);
let space = app.kovlet().open(&id, tables, store)?;
*st.space.lock().unwrap() = Some(space);
Ok(())
}
fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_kovlet::init("Todos"))
.setup(|app| {
let dir = app.path().app_data_dir()?;
std::fs::create_dir_all(&dir)?;
let db = Connection::open(dir.join("todos.db"))?;
db.execute_batch(
"CREATE TABLE IF NOT EXISTS todos (id TEXT PRIMARY KEY, title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0, deleted INTEGER NOT NULL DEFAULT 0)",
)?;
app.manage(AppState { db: Arc::new(Mutex::new(db)), space: Mutex::new(None) });
Ok(())
})
.invoke_handler(tauri::generate_handler![open_space])
.run(tauri::generate_context!())
.expect("error while running the app");
}You should see
- In plain Rust with the built-in store, a device code on the first run:
Open https://kovlet.com/activate and enter FHXJ-TFMW(your code differs). - Once you approve it,
rowsholds "Buy milk" at once. - A moment later,
rowsalso holds the rows every other app wrote to the sameTodosspace, such as the ones from the Node or REST quickstart. - In Tauri, the webview gets
kovlet://statusevents while it signs in and syncs.
How writes work
- Writes are write-through.
space.write("todos").upsert(&id, fields)updates your database before it returns, then syncs. fieldsis a patch, sojson!({ "done": true })changes one field.space.changes()is a broadcast receiver of changed table names. Forward it to the webview withapp.emit(...)to re-render.- Fields merge per field, and the later write wins.
Column types
The column builders are col::string(), col::number(), col::boolean(), col::datetime(), col::json(), col::file_ref() and col::reference("table"). Each takes .optional().
New tables and optional columns are created on open. Destructive changes become proposals an owner approves.
Step 5: FilesOptional
let f = space.files().put_file("photos/receipt.jpg", &local_path, "image/jpeg", None)?; // or put(path, &bytes, mime, None)
space.write("todos").upsert("t1", kovlet::serde_json::json!({ "photo": f.id }))?; // a col::file_ref() column
space.files().download(&f.id, &target_path).await?; // checks the SHA-256- Uploads are staged locally and sent in the background, so they work offline.
files().list(Some("photos/"))lists files on the server.move_to,deleteandrestoredo what they say.
To keep a whole folder in step with the space (attachments, say), use a mirror. Call let m = space.files().mirror(app_dir.join("attachments"), "attachments/")?; once, and m.notify_added("scan.png")?; after each write.
- It uploads what the space lacks and downloads what the folder lacks.
- It matches by path and SHA-256, so re-linking creates no duplicates.
- Deletes aren't mirrored.
Details are in the crate docs.
Step 6: Status and lifecycleOptional
- Status.
kovlet.watch_status()is awatch::Receiver<Status>withstateandpending. The states aresigned_out,authorizing,connecting,syncing,live,offlineanderror. - Events in Tauri. The plugin emits the status to the webview as
kovlet://status. It also emitskovlet://rejected,kovlet://error,kovlet://usage,kovlet://quotaandkovlet://transaction. - Pause and resume. The plugin pauses sync when every window is hidden or minimized, and resumes on focus. On exit it flushes the outboxThe client's queue of local writes not yet acknowledged by the server., the queue of writes not yet sent.
- Each part has its own switch on the builder:
pause_on_hide,pause_on_suspend(mobile) andexit_flush. A tray app that keeps syncing while hidden sets.pause_on_hide(false)and keeps the exit flush. - Without the plugin, call
kovlet.pause(grace).awaitandkovlet.resume()yourself. - Tests. In tests built with
tauri::test, pass.secret_store(Arc::new(kovlet::MemorySecretStore::new()))so sessions stay out of the OS keychain.
Step 7: Live queriesOptional
A live query keeps a result up to date as data changes. The client speaks sync protocol 2, where one socket per space carries many subscriptions.
A query is a JSON tree, like InstaQL:
- Top-level keys are tables.
- Nested keys follow
col::referencecolumns, forward or backward. $holdswhere,order,limitandfields.
The query language reference has the details.
use kovlet::serde_json::json;
let open = space.subscribe(json!({
"todos": { "quot;: { "where": { "done": false }, "order": { "createdAt": "desc" }, "limit": 50 }, "owner": {} }
}))?;
let _watch = open.observe(|result| println!("{:?}", result.data["todos"]))?; // built-in store: the nested tree- Full or partial copy.
open/open_builtinkeep a full replica (a"*"subscription) and run queries locally.client.open_query(&id, tables, store)keeps a partial replica: the server sends only the rows your subscriptions match. A row no subscription holds any more reaches yourapplyasChange::Purge. - Restarts. Subscriptions survive restarts and resume from their last cursor.
- Status.
open.unsubscribe()?ends one.open.status()showscomplete,moreand errors such asinvalid_query. - One-off queries.
space.query(&q)runs a query once over the built-in store, offline too, with the same matcher as the server.space.query_remote(q, None).awaitasks the server. - Older servers. A server that only speaks protocol 1 gets protocol 1 (a full replica), and the client remembers that for a day.
Client::builder(..).protocol(1)pins it.
Step 8: Atomic writesOptional
space.transact([...]) writes several rows all or nothing:
use kovlet::LocalWrite;
let tx = space.transact([
LocalWrite::upsert("teams", &team_id, json!({ "name": "Core" })),
LocalWrite::upsert("members", &member_id, json!({ "team": team_id, "role": "owner" })),
])?;
tx.settled().await?; // Ok("applied"), or the rejection- The writes apply to your database at once and go to the server as one batch. The server applies all of them or none.
- If it rejects the batch, every write rolls back together, as one
Origin::Rollbackbatch. - Queued writes to rows the batch created roll back too (
dependency_rejected). kovlet.events()deliversEvent::Transaction { status: "rejected", .. }.
Step 9: End users (public apps)Optional
A public app can sign people in without a Kovlet account. These people are end users. A space owner turns end-user sign-in on for your app in the console. app_id is your app's public ID.
let auth = kovlet.end_users(&space_id, "app_…");
auth.send_magic_code(&email).await?;
auth.sign_in_with_magic_code(&email, &code).await?; // or sign_in_as_guest(), sign_in_with_id_token(provider, token)
let space = kovlet.open_query(&space_id, tables, store)?;
let mine = space.subscribe(json!({ "todos": {} }))?; // only the rows the space's rules let them viewFrom the webview, the plugin's commands do the same:
invoke("plugin:kovlet|end_user_send_code", { spaceId, appId, email })sends the code.end_user_sign_inwithmethod: { method: "magic_code", email, code }signs in. The method can also be"guest","id_token"or"sign_in_code".end_user_sign_in_oauthwithprovideruses the system browser and the plugin's redirect. That redirect must be registered for the app.end_userreturns the signed-in end user.
Add them to the capability with the plugin's default permission.
How end-user sessions behave:
- The session is bound to the device key and refreshes by itself.
- End users always sync over protocol 2 with query subscriptions.
- The space's rules decide which rows arrive and which writes are accepted.
kovlet.sign_out()forgets every open space's synced rows and queued writes, so the next person on the device starts clean.
Local development
Run Kovlet locally starts kovletd --dev with Docker or the kovletd binary.
Run a local server that approves device codes on its own, and point the client at it:
kovletd --dev --dev-auto-approve # http://127.0.0.1:8080tauri_plugin_kovlet::Builder::new("Todos")
.base_url("http://127.0.0.1:8080")
.console_url("http://localhost:5173")
.build()
// plain Rust: Client::builder("Todos").base_url("http://127.0.0.1:8080").data_dir(&dir).build()?Without the SDK
A Rust app can also talk to Kovlet directly, without the crates. It uses device-code sign-in, REST for spaces and reads, and the WebSocket for writes and live sync. Start with the REST + WebSocket quickstart. The sync protocol reference covers every frame, merge rule and error.
Next
- Share live data between two AI-built apps: the tutorial that connects a second app to the same Data Space.
- Upload and sync files: versions, moves and the Trash.
- 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.