On this page

Building Truly Offline Apps Isn’t Magic: Local-First with Next.js, Flutter, and On-Device AI

A local-first architecture for Next.js and Flutter using write-ahead logs, deterministic reducers, optional sync, and on-device Gemma 3n inference.

Building Truly Offline Apps Isn’t Magic: Local-First with Next.js, Flutter, and On-Device AI

Starting a new app, most of us wire up the backend before we even sketch the core screens, then hope our offline mode "just works later." It rarely does. If you've ever patched cache misses, handled sync bugs, or watched your app freeze when Wi-Fi drops, you know why local-first development matters.

I decided to structure it around local storage from the start. Here's the blueprint I use for local-first in Next.js and Flutter, with an optional sync layer and Gemma 3n for offline inference on the device.

What does "local-first" actually mean?

Data on the device is always the source of truth. Your UI only ever talks to local storage. Everything else (cloud sync, cross-device sharing, even AI inference) is an add-on. If users lose connection, the app keeps working. If sync fails, data never disappears. If a user wants AI features, they run locally with no backend calls.

Core requirements

  • All app logic must work 100% offline (CRUD, search, inference)
  • Every mutation logs as an immutable operation (WAL pattern)
  • Deterministic reducers merge concurrent edits
  • Schema migrations never require cloud connectivity
  • Optional transport sync, with no functional dependency on it
Loading diagram...

Next.js implementation

1. Local storage: IndexedDB

I use IndexedDB via Dexie. There are two stores:

  • ops: Write-ahead log (append-only)
  • docs: Materialized current state

2. Reducer pattern

Every change is an operation object, appended to the WAL, then folded with a deterministic reducer to update docs.

ts
// IndexedDB setupimport Dexie from "dexie";const db = new Dexie("localfirst");db.version(1).stores({  ops: "++id,op_id,lamport_ts",  docs: "[coll+id],lamport_ts"});// Example opconst op = {  op_id: crypto.randomUUID(),  lamport_ts: Date.now(),  actor: "device_123",  kind: "todo.edit",  payload: { id: "a", title: "updated" }};await db.ops.add(op);// Then update docs via reducer

Reducers must be deterministic and order-independent where possible. For basic docs, I use "last writer wins" with per-field timestamps; for lists, I use CRDT sequences when I want rich merges.

3. Real-time reactivity

Hooks subscribe to batched WAL writes. Queries read straight from docs, so the UI is always current and responsive.

4. Schema migrations

On version bump, replay ops from the WAL, transform with the new reducer, write updated docs, and checkpoint the migration to avoid repeated work.

Flutter implementation

1. Local storage: Isar

On mobile, Isar fits well:

  • Op and Doc collections
  • ACID transactions, fast lookups
  • Migrations work by replaying the WAL and updating docs as needed

2. Operations and reducers

Each user interaction generates a serialized Op. Reducers update the current Doc record for that entity.

dart
@collectionclass Op {  Id id = Isar.autoIncrement;  late String opId;  late int lamportTs;  late String kind;  late Map<String, dynamic> payload;}

Reducer functions match op kind and materialize fields, using per-field timestamps for LWW or sequence CRDT logic for ordered updates.

3. UI and isolate sync

UI code subscribes to changes in docs via Isar queries. WAL writes and state reduction can run in a background isolate for performance, so rendering is never blocked by DB work.

Loading diagram...

Optional sync layer

If the user has multiple devices or wants backup, sync comes into play. The rule: if sync fails, users never notice. Everything keeps working.

How it works at a glance:

  • Client advertises vector clock of known ops
  • Pushes new ops in batches when online
  • Pulls missing ops from server (or other devices)
  • Server is just an append-only relay; no state reconciliation required

All actual merging is local; the code assumes nothing about server order or reliability.

Example sync client (Next.js)

ts
async function sync(endpoint: string) {  const known = await indexedOpsVectorClock();  const localOps = await getUnsentOps();  // Push local ops  await fetch(endpoint + "/push", { method: "POST", body: JSON.stringify(localOps) });  // Pull remote ops  const res = await fetch(endpoint + "/pull", { method: "POST", body: JSON.stringify({ known }) });  const remoteOps = await res.json();  // Append to WAL, replay as usual}

It stays as stateless and boring as possible: no conflict dialogs, no server arbitration.

Edge inference with Gemma 3n

Most "AI features" are just SaaS wrappers piping your data through a remote API. Here, the model runs on the device itself.

Packing Gemma 3n

  • For Next.js: Quantize the model, bundle it or fetch as needed, and load with ONNX Runtime for Web (WebGPU if available, Wasm fallback otherwise).
  • For Flutter: Quantized .tflite file, run with the TFLite Flutter plugin using NNAPI/CoreML delegates.

Workflow

  1. Download or bundle the model
  2. Tokenize inputs locally
  3. Run inference directly on-device
  4. Feed the result into normal app state (summarizing, recommending, etc.)

At the call site, both platforms reduce to loading the quantized artifact and passing tokenized input tensors into the runtime:

Web sketch (ONNX Runtime Web):

ts
import { InferenceSession } from "onnxruntime-web";const session = await InferenceSession.create("gemma3n_quant.onnx");// Build tokenized input tensors and call session.run(feeds)

Flutter sketch (TFLite):

dart
final interpreter = await Interpreter.fromAsset("gemma3n_quant.tflite");final result = interpreter.run(input, output);

No network calls, no PII leaves the device, and inference latency is predictable once the model is resident in memory.

Testing and reliability

With local-first, you get stronger test strategies:

  • Use property-based tests to shuffle ops, replay on multiple platforms, and assert convergence
  • Simulate random crashes (write half an op, crash, restart, and verify state)
  • Test schema migrations by replaying large synthetic WAL histories

Conclusion

Local-first means building logic, storage, and AI features around the premise that the user's device is the primary store. Sync, sharing, and cloud inference stay optional add-ons.

With Next.js, Flutter, optional WAL replication, and device-resident Gemma 3n, you get apps that don't lose data, never block the UI on network round-trips, run models offline, and treat sync as a convenience rather than a requirement.