Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: Offline Notes with Sync

Build an offline-first notes app in Expo: local SQLite as the source of truth, an outbox queue, delta sync with a server, conflict rules, deletions and background sync.

Mobile networks are unreliable, so the best apps work fully offline and sync when they can. This is called offline-first: the local database is the truth the UI reads and writes, and a sync engine reconciles it with the server in the background. The user never waits for the network and never loses a note typed in a tunnel.

This project designs a notes app with that architecture and builds the hard part, the sync engine, in plain JavaScript you can run and test here. It uses ideas from SQLite, networking and background tasks.

What runs on this site. Screens and native modules are read-only. The sync engine runs here against an in-memory fake server written in Node.js, which is also exactly how you would test it in your real project.

Architecture

flowchart LR
  UI["Screens"] -->|"read / write"| L["Local SQLite<br/>(source of truth)"]
  L --> O["Outbox<br/>(pending changes)"]
  O -->|"push"| S["Server API"]
  S -->|"pull changes since cursor"| L

Writes go to the local database first. The outbox remembers what the server has not seen yet.

Rules of the design:

  1. The UI never calls the server. It reads and writes local data only.
  2. Every change is recorded as an outbox entry (create, update, delete).
  3. Sync = push the outbox, then pull changes since the last cursor.
  4. IDs are generated on the device (UUIDs), so notes can be created offline without asking the server.
  5. Deletes are tombstones: a note is marked deleted, not erased, so the deletion can sync too.

The local schema

SQL
CREATE TABLE notes (
  id TEXT PRIMARY KEY,           -- UUID made on the device
  title TEXT NOT NULL,
  body TEXT NOT NULL DEFAULT '',
  updated_at INTEGER NOT NULL,   -- ms since epoch, set on every edit
  deleted INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE outbox (
  seq INTEGER PRIMARY KEY AUTOINCREMENT,
  note_id TEXT NOT NULL
);
CREATE TABLE sync_state (key TEXT PRIMARY KEY, value TEXT);   -- 'cursor'

The outbox just remembers which notes changed. At push time we send the current version of each, so ten edits to the same note become one upload.

The sync engine

Push first, then pull. The server decides conflicts with a simple rule, last write wins by updated_at: if the server already has a newer version of a note, it keeps its own and tells the client. This is easy to explain and good enough for personal notes. (For collaborative text you would use CRDTs or operational transforms, which are a topic of their own.)

Node.js Two devices syncing through a fake server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the result: both devices converge on the same list, the later edit won, and the deletion reached the tablet because it traveled as a tombstone, not as "the row vanished".

Handling failures

Real sync must survive interruptions:

  • Failed push: leave the outbox untouched and retry with backoff. Because the push is idempotent (same note id, same content), sending twice is harmless.
  • Pull interrupted: the cursor is saved only after the changes are applied, so the next run continues from the right place.
  • Server down: the UI is unaffected; show a small "Not synced" badge based on outbox size.
  • Many changes: push in batches of 50 to 100 to stay within time budgets of background tasks.
  • Clock skew: device clocks can be wrong. Many servers assign their own updated_at on accept. For the project, mention it as a known limitation, and prefer server time for ordering.
Node.js Retry with backoff and a battery of failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Connecting it to Expo

Where each piece lives in the app:

JSX
// src/sync.js (sketch)
import * as Network from 'expo-network';
import * as TaskManager from 'expo-task-manager';
import * as BackgroundTask from 'expo-background-task';
import { AppState } from 'react-native';

export async function syncNow(db) {
  const net = await Network.getNetworkStateAsync();
  if (!net.isConnected) return;
  await pushOutbox(db);
  await pullChanges(db);
}

// 1. When the app returns to the foreground
AppState.addEventListener('change', (s) => s === 'active' && syncNow(getDb()));

// 2. Right after the user saves (debounced)
// 3. Periodically in the background (best effort)
TaskManager.defineTask('notes-sync', async () => {
  try { await syncNow(await openDb()); return BackgroundTask.BackgroundTaskResult.Success; }
  catch { return BackgroundTask.BackgroundTaskResult.Failed; }
});

Screens subscribe to the local database (re-query after writes, or addDatabaseChangeListener), so a pull that brings new notes updates the list automatically.

Search and long lists

Notes accumulate. Use a LIKE query for simple search, or SQLite FTS5 (full-text search) where the build includes it, and render with FlatList (performance).

SQL
SELECT id, title FROM notes
WHERE deleted = 0 AND (title LIKE '%' || ?1 || '%' OR body LIKE '%' || ?1 || '%')
ORDER BY updated_at DESC LIMIT 50;

Security

  • Authenticate with a token kept in SecureStore (storage lesson).
  • Sync only the logged-in user's notes; the server must check ownership on every request.
  • If notes are sensitive, encrypt the database file or fields (for example with SQLCipher builds) and document it.
  • On logout, wipe the local database and outbox.

Extending the project

  1. Per-field merge, so title and body edits from two devices combine.
  2. Attachments uploaded separately with progress and resume.
  3. An "Offline" banner and a manual "Sync now" pull-to-refresh.
  4. Real-time updates over WebSocket, on top of the same engine.
  5. End-to-end tests of the engine with a fake server, like the one above.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In an offline-first app, what do screens read from?

    Local data is the source of truth; syncing happens in the background.
  2. 2. Why are note ids generated on the device?

    A client-generated unique id removes the need for a round trip.
  3. 3. Why use tombstones (a deleted flag) instead of removing rows?

    If the row just disappears, other devices cannot tell 'deleted' from 'never received'.
  4. 4. What makes retrying a push safe?

    Sending the same note id and content again yields the same server state.

Summary

  • Offline-first means local SQLite is the truth, and sync runs in the background.
  • Track changes in an outbox; push, then pull from a saved cursor.
  • Use client UUIDs, tombstones and a clear conflict rule such as last write wins.
  • Make every step retryable and idempotent; trigger sync on foreground, after saves and in background tasks.
  • Protect tokens, scope data to the user and wipe local data on logout.

Next: Project: a release pipeline