Tauri combines a Rust backend with any web frontend to produce native desktop applications. UUID v7 works in both layers — the Rust core generates UUIDs with the uuid crate, and the TypeScript frontend generates UUIDs with the uuid npm package. SQLite via tauri-plugin-sql stores them as TEXT primary keys. See UUID in Rust for the Rust UUID ecosystem.
Cargo.toml (src-tauri)
[dependencies]
tauri = { version = "2", features = [] }
uuid = { version = "1", features = ["v7"] }
serde = { version = "1", features = ["derive"] }
Rust command — generate UUID v7
// src-tauri/src/main.rs
use uuid::{Uuid, Timestamp, NoContext};
use std::time::{SystemTime, UNIX_EPOCH};
#[tauri::command]
fn new_uuid_v7() -> String {
let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let ts = Timestamp::from_unix(NoContext, d.as_secs(), d.subsec_nanos());
Uuid::new_v7(ts).to_string()
}
#[tauri::command]
fn extract_uuid_v7_timestamp(id: String) -> Option<u64> {
let hex = id.replace('-', "");
if hex.len() < 12 { return None; }
u64::from_str_radix(&hex[..12], 16).ok()
}
fn main() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![new_uuid_v7, extract_uuid_v7_timestamp])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
Frontend — call Rust command
import { invoke } from '@tauri-apps/api/core';
// Get UUID v7 from Rust backend (strongest randomness)
async function generateId(): Promise<string> {
return invoke<string>('new_uuid_v7');
}
// Or generate directly in the frontend (also safe in Tauri WebView)
import { v7 as uuidv7 } from 'uuid';
const id = uuidv7();
SQLite with tauri-plugin-sql
import Database from '@tauri-apps/plugin-sql';
import { v7 as uuidv7 } from 'uuid';
const db = await Database.load('sqlite:app.db');
// Initialize schema
await db.execute(`
CREATE TABLE IF NOT EXISTS notes (
id TEXT NOT NULL PRIMARY KEY,
title TEXT NOT NULL,
content TEXT NOT NULL DEFAULT '',
synced INTEGER NOT NULL DEFAULT 0
)
`);
// Insert with UUID v7 primary key
async function createNote(title: string, content: string) {
const id = uuidv7(); // UUID v7 — encodes creation time
await db.execute(
'INSERT INTO notes (id, title, content) VALUES ($1, $2, $3)',
[id, title, content]
);
return id;
}
// Cursor pagination — UUID v7 ORDER BY = chronological
async function listNotes(cursor?: string, limit = 20) {
const query = cursor
? 'SELECT id, title FROM notes WHERE id > $1 ORDER BY id LIMIT $2'
: 'SELECT id, title FROM notes ORDER BY id LIMIT $1';
const args = cursor ? [cursor, limit] : [limit];
return db.select<{ id: string; title: string }[]>(query, args);
}
Offline sync queue
// Queue actions locally — UUID v7 preserves action order for sync
async function queueAction(type: string, payload: object) {
const id = uuidv7(); // UUID v7 timestamp = when user performed the action
await db.execute(
'INSERT INTO sync_queue (id, type, payload) VALUES ($1, $2, $3)',
[id, type, JSON.stringify(payload)]
);
return id;
}
async function flushSync() {
const rows = await db.select<{ id: string; type: string; payload: string }[]>(
'SELECT * FROM sync_queue WHERE synced = 0 ORDER BY id'
// UUID v7 ORDER BY = replay actions in original order
);
for (const row of rows) {
await fetch('/api/sync', {
method: 'POST',
body: row.payload,
});
await db.execute('UPDATE sync_queue SET synced = 1 WHERE id = $1', [row.id]);
}
}
Extract timestamp in TypeScript
function extractTimestamp(id: string): Date {
const hex = id.replace(/-/g, '').slice(0, 12);
return new Date(parseInt(hex, 16));
}
// Show note age without a created_at column
const note = await db.select<{ id: string; title: string }[]>('SELECT id, title FROM notes WHERE id = $1', [noteId]);
const age = Date.now() - extractTimestamp(note[0].id).getTime();
console.log(`Note is ${Math.round(age / 1000)}s old`);
Further reading
- UUID in Rust — uuid Crate Guide
- UUID in SQLite
- UUID v7 in Distributed Systems
- UUID v7 for Cursor Pagination
- UUID v7 in Diesel ORM for Rust
External references
Frequently asked questions
Should I generate UUID v7 in Tauri's Rust backend or the frontend?
Either works. The Rust backend uses uuid = { version = "1", features = ["v7"] } with Uuid::new_v7(ts). The frontend uses import { v7 as uuidv7 } from 'uuid' — crypto.getRandomValues() is available in Tauri's WebView. Generating in the Rust backend gives stronger randomness guarantees; generating in the frontend enables optimistic UI patterns before the IPC round-trip completes. See UUID in Rust.
How do I use UUID v7 with tauri-plugin-sql and SQLite?
The plugin exposes db.execute(sql, values) to the frontend. Use UUID v7 strings as TEXT primary keys: db.execute("INSERT INTO items (id, name) VALUES ($1, $2)", [uuidv7(), name]). SQLite TEXT sorts lexicographically — UUID v7 lexicographic order equals chronological, so SELECT * FROM items ORDER BY id returns items in creation order. See UUID in SQLite.
How does UUID v7 help with Tauri offline-first sync?
Tauri desktop apps may work offline for extended periods. UUID v7 generated on the device carries a timestamp — when the app reconnects and syncs with a server, records from the local SQLite database merge with server records in chronological order by UUID v7 sort. No server-assigned IDs or sequence numbers are needed for ordering. See UUID v7 in Distributed Systems.