User Identification
The ORM stores a stable visitor identifier (a UUID) under the "user" key in IndexedDB as { visitor_uuid: "…" }. The preferred way to read and write it is via the store singleton.
import { store } from "@superbright/indexeddb-orm";
store.getVisitorUUID
const uuid = await store.getVisitorUUID();
// → string | null
Reads visitor_uuid from the "user" KV entry. Returns null when no UUID has been persisted yet.
store.setVisitorUUID
await store.setVisitorUUID("550e8400-e29b-41d4-a716-446655440000");
Persists visitor_uuid inside the "user" KV entry, safely merging with any other fields stored there.
Recommended pattern: useVisitorSession
In React apps the visitor UUID is typically resolved via the useVisitorSession hook, which:
- Reads
visitor_uuidfrom IndexedDB viastore.getVisitorUUID(). - If the read returns
null, callsPOST /embed/{slug}/sessionto obtain a fresh UUID from the API and persists it withstore.setVisitorUUID().
The hook returns string | undefined (undefined while loading) and the result is passed directly to AnalyticsProvider as the visitor_uuid prop. See the Analytics docs for the full implementation.
Legacy helpers
The functions below predate the store API. They remain available for backwards compatibility but the store methods above are preferred.
ensureUser
import { ensureUser } from "@superbright/indexeddb-orm";
const user = await ensureUser();
console.log(user.uuid); // stable UUID across sessions on the same browser
- Generates a v4 UUID using
crypto.randomUUIDwhen available, with a secure fallback. - Stores a pointer record in the
kvtable and a row in theuserstable. - Uses a read/write Dexie transaction to avoid races when multiple tabs open at once.
- Accepts an optional custom ID generator, useful for deterministic tests.
getUserUUID
const uuid = await getUserUUID();
Returns only the uuid string, delegating to ensureUser under the hood.
Custom ID generation
const mockId = () => "test-user";
await ensureUser(mockId);
Useful in tests where IndexedDB is mocked and deterministic IDs simplify assertions.