DEV Community

Cover image for Building an offline-first React Native app with Turso Sync, Measure and Claude Code
Kathank Raithatha for Studio1

Posted on Edited on

Building an offline-first React Native app with Turso Sync, Measure and Claude Code

TL;DR

  • I built SyncNote, an offline-first notes app in React Native and Expo.
  • Turso Sync stores the notes in a local database on the phone and syncs it with the cloud.
  • Measure adds mobile observability: events, traces, errors, network calls and bug reports from the device.
  • When a sync failed, Claude Code used the Measure MCP server to read the session and find the cause.
  • All numbers and screenshots come from a real run on an Android emulator.

What an offline-first app has to get right

SyncNote is a notes app for teams that work without a reliable connection. Field technicians on a site visit. Consultants writing notes on a flight. Anyone editing a shared doc on a train.

For the engineering team, that turns into four requirements:

Requirement What goes wrong without it
Saves work offline and survive an app kill Users lose edits when a save waits on the network
Changes from other devices arrive quickly Users edit an old version of the note
The UI stays fast on a bad network A slow sync blocks typing and saving
Two edits to the same note are handled One edit is overwritten and nobody knows

Turso Sync covers the data side of the first three. The fourth needs app logic.

There's a fifth problem that doesn't fit in the table. Once the app ships, it runs on phones you don't control. Different models, Android versions and networks. On a backend, you have logs and metrics on servers you own. On mobile, when sync breaks on a user's phone, you usually get a one-line support ticket and nothing else.

Offline-first makes this harder. A failure can happen on a plane and only show up hours later, when the phone reconnects. And most sync problems don't crash the app, so crash reporting alone won't catch them. You need a record of the session: what the user did, whether the phone was online, and what each sync attempt did.

That's the part Measure handles in this app.

The stack

  • React Native + Expo (SDK 58): the app, written in TypeScript and run as a development build.
  • Turso Sync : a local SQLite database on the device that syncs with Turso Cloud.
  • Measure : open-source mobile observability, added through an Expo config plugin.
  • NetInfo: tells the app when the device goes online or offline.
  • Claude Code with the Measure MCP server: reads production data and helps debug it.

Both SDKs include native code, so Expo Go can't run them. You need a development build.

NOTE: EXPO_PUBLIC_* values are bundled into the app, so this demo ships a Turso auth token inside the client. Don't do that in production. Issue short-lived tokens from your backend instead.

How SyncNote is wired: the phone holds the UI, the local database, the sync engine and the Measure SDK. Turso Cloud and a laptop sit on one side, Measure and Claude Code on the other.

The app only reads and writes the local database. Sync, telemetry and debugging happen around it.

Storing data on the device with Turso Sync

Turso Sync gives each device its own local database file. The app reads and writes that file, and syncs it with Turso Cloud when a connection is available. That is the model I wanted, so the whole data layer is one file on the phone.

// src/db.ts
import { Database, getDbPath } from '@tursodatabase/sync-react-native';

const notesDb = new Database({
  path: getDbPath('syncnote.db'),        // SQLite file on the device
  url: process.env.EXPO_PUBLIC_TURSO_URL, // libsql://<db>.turso.io
  authToken: process.env.EXPO_PUBLIC_TURSO_AUTH_TOKEN,
  clientName: `syncnote-${deviceId}`,
  bootstrapIfEmpty: true,                 // first launch downloads the DB once
});
await notesDb.connect();
Enter fullscreen mode Exit fullscreen mode

Saving a note is a normal local write. It works the same on Wi-Fi, on 2G and in airplane mode. There is no loading spinner and no separate offline mode.

await notesDb.run(
  'UPDATE notes SET title = ?, content = ?, rev = ?, updated_at = ?, updated_by = ? WHERE id = ?',
  [title, content, rev, Date.now(), deviceId, id],
);
Enter fullscreen mode Exit fullscreen mode

Syncing is two calls:

await notesDb.push();                   // send local changes to Turso Cloud
const changed = await notesDb.pull();   // apply changes from other devices
const stats = await notesDb.stats();    // pending changes, last pull time, bytes
Enter fullscreen mode Exit fullscreen mode

The app syncs after each save when online, and again when the device reconnects. While the app is open, it also pulls every 5 seconds. In my test, a laptop edit showed up on the phone in about 4.4 seconds. Most of that was waiting for the next 5-second poll. The pull itself took 345 ms and downloaded about 4 KB. Turso also supports long polling on pull (longPollTimeoutMs), which I didn't try here.

Handling two edits to the same note

Turso Sync resolves conflicts with last push wins. If two devices change the same row, the server keeps whichever push arrives last. On pull, Turso rolls back your unpushed changes, applies the remote ones, and replays yours on top.

That is a reasonable default, and many apps can live with it. For shared notes, I wanted users to know when it happens. If I edit a note offline and a teammate edits it online, one edit gets overwritten and the app never hears about it.

So I added a revision check before each push:

  1. Every note has a rev number.
  2. The first offline edit stores the base_rev it started from.
  3. Before pushing, the app asks Turso Cloud which revision the server has.
  4. If the server is ahead of base_rev, the app stops the push and shows both versions.
// src/store.tsx (simplified)
const remote = await fetchRemoteNotes(pendingUpdates.map((u) => u.note_id));
const conflicts = pendingUpdates.filter((u) => (remote.get(u.note_id)?.rev ?? 0) > u.base_rev);

if (conflicts.length) {
  track('sync_conflict_detected', { note_id, base_rev, remote_rev, remote_updated_by });
  throw new SyncConflictError(conflicts);   // nothing is pushed
}
await notesDb.push();
await notesDb.pull();
Enter fullscreen mode Exit fullscreen mode

What happens when the phone reconnects: reconnect, ask the server for its revision, then push and pull. The red branch shows the conflict path.

Turso handles push and pull. The revision check between them is app code.

To be clear about the split: storage, sync and conflict resolution come from Turso. The revision check and the "Keep mine / Use theirs" screen are my code.

The check has one gap. It runs before push(), not inside it. If another device writes in the short window between the check and the push, last push wins still applies. That was fine for a demo, but worth knowing.

Adding mobile observability with Measure

Sync bugs happen on users' phones, on networks I can't reproduce at my end. To see them, I used Measure, an open-source mobile observability platform. You can self-host it.

Measure captures crashes and ANRs automatically. For this project, the more useful part was the session timeline. It shows screens, taps, network calls, logs and my own events in order. Sync problems rarely crash the app, so crash reporting alone would miss them.

Setup

Measure ships an Expo config plugin:

// app.config.ts
plugins: [
  ['@measuresh/react-native', {
    androidApiKey: process.env.MEASURE_API_KEY,
    androidApiUrl: process.env.MEASURE_API_URL,
    iosApiKey: process.env.MEASURE_API_KEY,
    iosApiUrl: process.env.MEASURE_API_URL,
  }],
],
Enter fullscreen mode Exit fullscreen mode
// src/telemetry.ts
import { Measure, MeasureConfig } from '@measuresh/react-native';
await Measure.init({ config: new MeasureConfig({ enableLogging: __DEV__ }) });
Enter fullscreen mode Exit fullscreen mode

On Android, the plugin also adds Measure's OkHttp interceptor. Without it, network monitoring doesn't capture HTTP calls.

What I track

All tracking code is in one file, src/telemetry.ts. It never sends note text. Only ids, revision numbers, lengths, counts and timings.

Events mark each step of a sync:

track('note_saved_locally', { note_id, is_online: false, local_write_ms: 41.1, base_rev: 6 });
track('connectivity_changed', { is_online: true, connection_type: 'cellular', offline_duration_ms: 33324 });
track('sync_started', { trigger: 'reconnect', turso_cdc_operations: 1, replica_last_pull_age_ms: 84526 });
Enter fullscreen mode Exit fullscreen mode

The last two fields in sync_started come from Turso's stats(). They show how many changes were waiting, and how long since the device last pulled. When debugging the conflict later, turso_cdc_operations: 1 confirmed there was exactly one unpushed change.

local_write_ms measures my whole save function, not just Turso's write. It includes a read, the write, and a second write to a local-only queue table, all in a debug build. So treat it as an upper bound for the app, not a Turso benchmark.

Traces time each sync. These are app-side spans that wrap my calls to the Turso SDK. They are not Turso's internal traces. Each sync is a sync trace with one child span per phase:

const root = Measure.startSpan({ name: 'sync' });
const push = Measure.startSpan({ name: 'sync.push' }).setParent(root);
await notesDb.push();
push.setStatus(SpanStatus.Ok).end();
root.setStatus(SpanStatus.Ok).end();
Enter fullscreen mode Exit fullscreen mode

In my test sessions, sync.live_pull took 259 ms at p50 and 1.3 s at p95. A full sync took 2.26 s at p50. That's from a handful of runs on one emulator, so read it as a sanity check, not a benchmark.

Handled errors carry context about where the sync failed:

Measure.trackError({ error, attributes: { phase: 'push', reason: 'network', connection_type: 'cellular' } });
Enter fullscreen mode Exit fullscreen mode

Measure groups errors by type, message and top stack frame. Conflicts, slow syncs and network failures each got their own group.

Measure samples handled errors at 0% by default. I ran this demo with full collection on. In production, raise the rate for the errors you care about.

Network calls need no extra code. The Turso SDK makes HTTP requests from the app, and Measure records them on the session timeline with status codes and durations. POST /pull-updates is Turso's pull. POST /v2/pipeline is used by Turso's push and also by my revision check. Measure never collects the Authorization header. I checked the raw session data, and the Turso token was not there.

Bug reports from users

Measure.launchBugReport({ takeScreenshot: true, attributes: { screen, pending_count, sync_status } });
Measure.onShake({ handler: () => Measure.launchBugReport({ takeScreenshot: true }) });
Enter fullscreen mode Exit fullscreen mode

A bug report opens a native screen with a screenshot attached. Text in the screenshot is masked by default. The report is linked to the session, so you can replay what happened before it.

Measure's in-app bug report screen on React Native, with the attached screenshot masked

The bug report screen. Note text in the screenshot is masked.

Testing four scenarios on an Android emulator

I ran these tests on an Android 12 (API 31) emulator, with a Turso Cloud database and Measure. It was a debug build.

1. Saving while offline

I turned on airplane mode, edited a note and saved it. Then I force-killed the app and opened it again, still offline.

The note editor showing "Saved on this device, will sync when online" while offline

Saved offline. The sync status shows Pending.

The notes list after reopening the app offline, with the edit still there

After a force-kill and reopen, the edit is still there.

The edit survived the restart. In Measure, the session shows note_saved_locally with is_online: false and local_write_ms: 45.5. Then app_opened with one pending change.

2. An edit from another device

With the phone online, a second client edited the same note in Turso Cloud. I used a Node script to act as the laptop. The server saved the change at 00:40:40.7. The phone showed it at 00:40:45.1.

The notes list with a badge reading "Updated from laptop-web-client"

The next pull brought the change in 345 ms, using 4,165 bytes.

3. A slow network

I throttled the emulator to GSM speed with GPRS latency, and turned Wi-Fi off so the limit applied.

The editor showing "Saved" while the sync status still says "Syncing"

Saved in 41 ms, while sync is still running.

Saving was instant but Sync failed. Measure recorded each step:

  • SlowSyncError when the push passed the app's own 8-second budget
  • a java.io.IOException: unexpected end of stream from the push request, after 31.5 s. The throttled connection dropped, and the Turso SDK passed the network error up to the app. The app logged it as sync_failed with phase: push
  • a sync_completed that took 66.9 s once the edit finally synced

Bar chart: a 41 ms local save next to a 66.9 second sync on a throttled network

Same app on the same emulator. Only the network changed.

The app never crashed, so crash reporting would show nothing here. The traces and handled errors are what made the slow sync visible.

4. Two people editing the same note

  1. On the phone, offline, I edited the note. The edit started from rev 6.
  2. On the laptop, a second edit moved the server to rev 7.
  3. The phone reconnected and started syncing.

The notes list with a "Sync conflict" banner after reconnecting

The conflict is detected on reconnect.

The conflict card showing both versions of the note, with Keep mine and Use theirs buttons

Both versions are shown, and the user picks one.

The revision check stopped the push about 2 seconds after reconnecting. The sync itself ran for 1.3 s before it failed. Without the check, the laptop's edit would have been overwritten.

Next, I filed a bug report from the app: "Edited Launch Plan on the plane. After landing it says sync conflict. Which version is right?" Then I tapped Keep mine. The server ended at rev 8 with the phone's text.

Debugging the sync failure with Claude Code and the Measure MCP server

The Measure MCP server lets coding agents query an app's sessions, errors, traces and bug reports. I connected it to Claude Code with this command:

claude mcp add --transport http measure https://agent.measure.sh/mcp
Enter fullscreen mode Exit fullscreen mode

Then I gave this prompt to Claude Code:

A user filed a bug report about a sync conflict. Find it, analyze the session
timeline, connectivity changes, sync attempts and conflict events, identify
the root cause and suggest a fix.
Enter fullscreen mode Exit fullscreen mode

The steps Claude Code took: find the bug report, open its session, read the errors, read the sync code, then explain the cause

The MCP calls Claude made, and the source file it read.

It found the bug report, opened the linked session and rebuilt the timeline:

A timeline of one session: the app opens offline, comes back online 33 seconds after launch, conflict detected, bug report filed, then resolved and synced

Each label is a real event from the session.

Here is a short version of its answer:

  • What happened: the session started offline with one unpushed change, and the phone reconnected 33 seconds later. That edit started from rev 6. While the phone was offline, the laptop saved rev 7. On reconnect, the revision check saw rev 7 and blocked the push.
  • Root cause: two people edited the same note while one was offline. Turso Sync uses last push wins, and the app has no merge step. It can only ask the user to pick a version.
  • Suggested fixes:
    • Merge the two texts, using rev 6 as the common base (a three-way merge).
    • Track revisions per paragraph instead of per note.
    • Warn the user before editing if the note changed on another device.

I could check each point against an event, an error group or a line in store.tsx. That works because the app logs revisions, device ids and Turso's stats, not just "sync failed".

Claude also found an unhandled ReferenceError in the error list. That was my bug. Fast Refresh had loaded a half-finished edit, and Measure caught the error with no extra setup.

Finally, I asked Claude to create a funnel through the MCP server: note_saved_locally → connectivity_changed → sync_started → sync_failed → conflict_resolved → sync_completed. With one test user, the time between steps was 51 s, 0.9 s, 1.3 s and 58 s. With real users, the medians would show how long people stay stuck on a conflict.

Results

Measurement Result Source
App save function (debug build) 41–46 ms note_saved_locally
Laptop edit visible on phone about 4.4 s (mostly the 5 s poll) wall clock
Live pull p50 259 ms, p95 1.3 s Measure span metrics
Sync on a normal network about 0.9–1.2 s sync_completed
Sync on throttled GSM failed at 31.5 s, succeeded at 66.9 s sync_failed, sync_completed
Conflict detected after reconnect 2.2 s (1.3 s into the sync) sync_failed
Note text or auth token in telemetry none found raw session data

If you want to check the demo implementation, refer here


FAQ

Does Turso Sync work offline in React Native and Expo?

Yes. The first launch needs a connection to download the database. After that, reads and writes go to a local file. Changes stay there until you call push(). You need an Expo development build, not Expo Go.

How does Turso Sync handle conflicts?

With last push wins. On pull, unpushed local changes are rolled back, remote changes are applied, and local changes are replayed on top. The React Native package I used (0.8.3) doesn't expose a conflict hook. So to detect concurrent edits, I added a version column and checked it before pushing.

Can I use Measure with Expo?

Yes. The @measuresh/react-native package includes an Expo config plugin. It sets your API keys, starts the native SDKs and enables HTTP capture on Android.

How does Measure compare to Firebase Crashlytics or Sentry for React Native?

All three report crashes and Android ANRs. Crashlytics only reports ANRs from Android 11 and later. The differences are elsewhere:

  • Network calls. Measure and Sentry capture HTTP requests automatically. Crashlytics doesn't. That needs Firebase Performance Monitoring, a separate product.
  • User feedback. Measure and Sentry both have an in-app bug report with screenshots. I couldn't find an equivalent in Crashlytics.
  • Hosting. Measure is open source under Apache 2.0 and can be self-hosted. Sentry can also be self-hosted, under its Functional Source License. Crashlytics runs on Google's servers only.
  • React Native SDK. Measure and Sentry maintain their own React Native SDKs. The Crashlytics package for React Native (@react-native-firebase/crashlytics) is maintained by Invertase, not Google.

None of them runs fully in Expo Go. All three use a config plugin and a development build. For this project I picked Measure because I wanted open source with a self-host option, and a session timeline with my own events on it.

What does the Measure MCP server do?

Measure MCP Server lets AI coding agents like Claude Code, Cursor and Codex query your app's errors, sessions, traces, bug reports and funnels. The agent works from what happened on real devices, so it doesn't have to guess. Sentry and Firebase have MCP servers too, so this way of working isn't tied to one vendor.


If you love my content ❤️ Follow me on LinkedIn
~ Kathank Raithatha

Top comments (1)

Collapse
 
shivaylamba profile image
Shivay Lamba •

This is amazing. Really loved reading this article, Kathank. Thank you for sharing.