Expo and React Native applications routinely create records offline — local SQLite rows, queued API requests, analytics events — before any server interaction. UUID v7 generated on-device gives each record a globally unique, time-ordered identifier that merges cleanly with server data during sync. See UUID in Mobile Apps for the broader mobile context.
Setup — polyfill and uuid package
npx expo install react-native-get-random-values uuid
// App.tsx or index.ts — import polyfill FIRST
import 'react-native-get-random-values';
import { v7 as uuidv7 } from 'uuid';
// Now safe to use anywhere in the app
const id = uuidv7();
Expo SQLite with UUID v7 primary keys
import * as SQLite from 'expo-sqlite';
import { v7 as uuidv7 } from 'uuid';
const db = SQLite.openDatabaseSync('app.db');
// Create table with TEXT UUID v7 primary key
db.execSync(`
CREATE TABLE IF NOT EXISTS tasks (
id TEXT NOT NULL PRIMARY KEY,
title TEXT NOT NULL,
done INTEGER NOT NULL DEFAULT 0,
synced INTEGER NOT NULL DEFAULT 0
)
`);
// Insert — UUID v7 as PK, encodes creation time
function createTask(title: string) {
const id = uuidv7();
db.runSync(
'INSERT INTO tasks (id, title) VALUES (?, ?)',
id, title
);
return id;
}
// Cursor pagination — UUID v7 TEXT sort = chronological
function listTasks(cursor?: string, limit = 20) {
const query = cursor
? 'SELECT * FROM tasks WHERE id > ? ORDER BY id LIMIT ?'
: 'SELECT * FROM tasks ORDER BY id LIMIT ?';
const args = cursor ? [cursor, limit] : [limit];
return db.getAllSync(query, ...args);
}
See UUID in SQLite for storage details.
Offline sync queue with UUID v7
import { v7 as uuidv7 } from 'uuid';
interface SyncRecord {
id: string; // UUID v7 — creation time embedded
operation: 'create' | 'update' | 'delete';
entity: string;
payload: unknown;
syncedAt: number | null;
}
// Create record offline — UUID v7 assigned before network exists
function queueOperation(operation: SyncRecord['operation'], entity: string, payload: unknown) {
const record: SyncRecord = {
id: uuidv7(), // timestamp encodes when the action occurred
operation,
entity,
payload,
syncedAt: null,
};
db.runSync(
'INSERT INTO sync_queue (id, operation, entity, payload, synced_at) VALUES (?, ?, ?, ?, ?)',
record.id, record.operation, record.entity, JSON.stringify(record.payload), null
);
return record;
}
// Flush queue — UUID v7 ORDER BY = operations in creation order
async function flushQueue() {
const pending = db.getAllSync<SyncRecord>(
'SELECT * FROM sync_queue WHERE synced_at IS NULL ORDER BY id'
);
for (const record of pending) {
await sendToServer(record);
db.runSync(
'UPDATE sync_queue SET synced_at = ? WHERE id = ?',
Date.now(), record.id
);
}
}
AsyncStorage session ID with UUID v7
import AsyncStorage from '@react-native-async-storage/async-storage';
import { v7 as uuidv7 } from 'uuid';
const SESSION_KEY = '@session_id';
// Get or create a UUID v7 session ID — persists across app restarts
export async function getSessionId(): Promise<string> {
let sessionId = await AsyncStorage.getItem(SESSION_KEY);
if (!sessionId) {
sessionId = uuidv7(); // UUID v7 — encodes session start time
await AsyncStorage.setItem(SESSION_KEY, sessionId);
}
return sessionId;
}
// Extract session start time from UUID v7
export function getSessionStartTime(sessionId: string): Date {
const hex = sessionId.replace(/-/g, '').slice(0, 12);
return new Date(parseInt(hex, 16));
}
Analytics event with UUID v7
interface AnalyticsEvent {
id: string; // UUID v7 — event time embedded
sessionId: string;
event: string;
properties: Record<string, unknown>;
}
async function trackEvent(event: string, properties = {}) {
const sessionId = await getSessionId();
const payload: AnalyticsEvent = {
id: uuidv7(), // per-event UUID v7
sessionId,
event,
properties,
};
// Queue for batch send; UUID v7 ordering = event timeline
await queueAnalyticsEvent(payload);
}
Further reading
- UUID in Mobile Apps
- UUID in SQLite
- UUID v7 in Distributed Systems
- UUID in JavaScript
- UUID v7 for Cursor Pagination
External references
Frequently asked questions
How do I generate UUID v7 in a React Native or Expo app?
Install the uuid npm package and the react-native-get-random-values polyfill. Import the polyfill before uuid: import 'react-native-get-random-values' then import { v7 as uuidv7 } from 'uuid'. The polyfill provides crypto.getRandomValues() which uuid requires. In Expo SDK 50+, expo-crypto also provides randomUUID() (UUID v4 only), so use the uuid package for v7. See UUID in JavaScript.
How does UUID v7 help with offline-first sync in React Native?
In offline-first apps, records are created on-device before reaching the server. UUID v7 generated on the device carries a timestamp, so when the sync queue is flushed to the server, records from multiple devices merge into chronological order without coordination. UUID v4 sorts randomly — UUID v7 sorts by device creation time. See UUID v7 in Distributed Systems.
Can I use UUID v7 as a primary key in Expo SQLite?
Yes. Expo SQLite (expo-sqlite v13+) supports TEXT primary keys. Use CREATE TABLE items (id TEXT PRIMARY KEY, ...) and insert UUID v7 strings generated with the uuid npm package. UUID v7 TEXT sorts lexicographically in SQLite, giving chronological ORDER BY id without a created_at column. See UUID in SQLite.