Offline data for Meteor PWAs: what ships in 3.6, what comes next, and your requirements

This topic continues the offline discussion from the Meteor on Bun thread (Meteor on Bun: ESM bundle, native host, and initial benchmarks - #13 by dupontbertrand), so it gets its own place.

TL;DR

  • Meteor 3.6 (currently in release candidate) ships meteor create --pwa: an installable Blaze app with a manifest, icons, a dependency-free service worker and an offline fallback page.
  • It does not sync data offline. That is the next layer, and a working prototype exists: it keeps a copy of your published data on the device, queues Method calls while offline and replays them on reconnect.
  • The plan is PWAs first, opt-in: at creation time, or by adding a dedicated package to an existing app.
  • Before writing more code, I want your requirements: what has to work offline in your apps, and what must never happen.

Context

Offline is one of the most requested features, and the community already has good answers: jam:offline is documented in the Meteor docs, and the notes-offline example combines it with Workbox. What is missing is a batteries-included path in core, starting with a scaffold that works out of the box. I am working on PWAs, so offline data is the natural next step. It is also a hard topic: storage limits on the device, security of the data kept there, and how it plugs into DDP, Methods and Minimongo.

Already done: meteor create --pwa (Meteor 3.6, feat(cli): add 'meteor create --pwa' for an installable Blaze PWA by dupontbertrand · Pull Request #14473 · meteor/meteor · GitHub)

  • Blaze app with a web app manifest, three icons (one maskable) and install support.
  • A hand-written service worker with no dependencies. In production: network-first navigation with offline.html as fallback, stale-while-revalidate for hashed bundles, cache-first for images and fonts.
  • In development the worker only precaches its static files, so hot code push never reuses a stale bundle.
  • DDP traffic (/sockjs/ and /websocket) is never intercepted, and a path-prefixed ROOT_URL works unchanged.
  • Covered by E2E tests and documented in the meteor create docs.

Already done: offline data prototype (not in a PR yet)

  • The server stays the source of truth.
  • Reads: the documents your publications already send are mirrored into IndexedDB. On the next start, Minimongo is filled from that copy before the connection is up, and Meteor’s normal reconnect brings it back in line with the server. The device only keeps what your publications send, so the server does no extra work to fill it.
  • Writes: Methods you explicitly allow are applied locally while offline, stored in a durable queue in IndexedDB, and replayed on reconnect. The server Method is idempotent, so a replay never creates a duplicate. Everything not allowed keeps the normal behavior.
  • One configuration call: which collections to keep, which Methods may run offline, and how each one writes locally.
  • Validated on desktop (write offline, reload, reconnect: the write lands exactly once) and installed on a real phone.
  • No change to Meteor core so far.

What I want to do

  • Finish the engine: updates and removes (inserts only so far), and clearing the device copy when the signed-in user changes (first version written, not yet tested with real account switches).
  • Replace the prototype’s interception of Method calls with a small, documented hook in the DDP client, so the engine does not depend on internals.
  • Ship it opt-in for PWAs: as an option of meteor create --pwa, and as a package you add to an existing app.
  • Outside PWAs: possible later, not in the coming weeks.

Where I need you

  • What data must be available offline in your app, and roughly how much?
  • Which writes must work offline, and how should a conflict be resolved when the server changed in between?
  • Security: what may stay on a shared device, and what must disappear on logout?
  • What do you use today (jam:offline, GroundDB, custom code), and what hurts?
  • If you need this outside the browser (React Native, Capacitor), which storage do you use?

@waldgeist @xet7 your messages started this, so your input is especially welcome :hand_with_index_finger_and_thumb_crossed:

3 Likes

@dupontbertrand

What data must be available offline in your app, and roughly how much?

It should be selectable by user.

Some kanban boards have thousands of cards, big attachments (someone uploaded Windows .iso files about 5 GB to card), etc. :wink:

For features need to work offline, that code also should also be included to offline.html , so that meteor create --pwa should have working example of that.

History is needed for undo/redo , and adding offline changes to that history. When adding offline changes to history, each change needs to be validated so that only allowed changes are applied. For example, if at offline history card has been moved to different list, and meanwhile destination list has already been moved to different board? This maybe needs some IFTTT Rules about what happens at each case.

What do you use today (jam:offline, GroundDB, custom code), and what hurts?

It hurts when there is some feedback that big boards loads too slow, or that some have experienced performance issues. In next WeKan there is more optimizations, so that file operations would always use streaming, and not load a lot of data to RAM, more optimized database queries, only lazy load some code when needed, only load visible required data to browserside, etc.

1 Like

Love this direction, great work! As a long-time Blaze user, I also appreciate that it’s still alive and kicking. Personally, I’ve moved on to React a long time ago, though (as a result of Geoff’s post back in the days), so I’d love to see the same offline support for React / React Native as well. But I guess that would be perfectly doable, as Meteor is not tied to any specific front-end framework.

Regarding your questions:

  • I’m working on a React Native app where basically all user-specific data will have to be offline. Not only app state, but also database content and binary files (images, PDF documents). I am currently evaluating linking LiveStore to my Meteor backend for the database part and solve the binaries part using S3 as I did for my main project.
  • For my app, conflict resolving could be easy, because the user-specific content is only writable by the user, other users have only read access. It could happen, though, that the user works on web and mobile in parallel. I am thinking of a mechanism that works like JetBrain Sync, so the user decides which version “wins” if a conflict happens.
  • Security: I want all user data to stay on device, so a secure storage for the database stuff is necessary. Most existing solutions in the React Native realm offer this via SQLite.
  • I wasn’t aware of `jam:offline`, will have a look into it. This might come in handy for my main app, where I’d love to see some (temporary) offline support as well. It’s an outdoor app, and the biggest challenge is that there is not always a stable mobile connection if you’re hiking off-grid.
  • I plan to use LiveStore, but it’s in an early beta stage.
2 Likes

@xet7 @waldgeist thanks a lot for taking the time, this is exactly what I needed :folded_hands:

Quick status first: Meteor 3.6 is at rc.1 with meteor create --pwa in it. The offline engine won’t make it into 3.6 (feature freeze), so it’s aiming at 3.7. Same idea as before: the server stays the source of truth, the device keeps a copy of what your publications send, and the Methods you allow are queued while offline and replayed on reconnect. If you need offline data today, jam:offline is the way to go, and the notes-offline example shows it wired with Workbox.

@xet7

Selectable by user: yes! The device only keeps the collections you declare, and for those only the documents your publications send to that user. The engine never fetches anything on its own, so no extra load on the server, and the copy is bounded by what you already publish. A “keep this board offline” toggle is just a subscription on your side.

The 5 GB .iso :sweat_smile: Attachments are out of scope, the engine stores documents, not files. Browser quotas are all over the place and a file that size has no business in a device copy. Files stay on the server, or in a service worker cache of your own for the few that really need to be available offline.

About offline.html: no need to put any code in there :slight_smile: In production the worker serves the app shell and the bundle it cached on a previous visit, so the whole app runs offline, data layer included. offline.html only shows up for a page the device has never loaded. The skeleton’s E2E actually stops the server and reloads the app from the cache to check exactly that.

Undo/redo and validation: validation stays on the server. A replayed Method runs the same code as an online call, same checks, same permissions, so your “card moved to a list that moved to another board” case is decided by your server rules, not by the device. What the engine guarantees is that each queued call replays once, in order. Right now a rejected call stops the queue and retries on the next reconnect; for a case like yours, dropping it and telling the user is better, so that’s what I’m going for. And the queue is readable by the app: pending calls are plain records in IndexedDB (name, args, timestamp), so you can list them, undo one before it replays, or feed them into WeKan’s history. The engine doesn’t own history.

Big boards: the device copy makes reloads instant for what’s already there (Minimongo is filled from the device before the connection is up, then the normal reconnect reconciles). And there’s no sync query on the server at all, no updatedAt scan, none of the full-collection scans you ran into with jam:offline’s defaults. The only server work is the publication you already run. Your security points from the Bun thread are on the requirements list: clear the copy on logout or account switch, and never keep anything that isn’t published to the user.

@waldgeist

React / React Native: I’ll keep this one Blaze-in-the-browser, that’s what I can build and maintain :blush: The engine itself sits between DDP, Minimongo and IndexedDB and doesn’t care about the view layer, so a React web app is more a packaging question than a design one, and anyone who wants to take it there is welcome. React Native is another runtime though (no IndexedDB, no service worker, its own storage), so I’ll leave that one alone. LiveStore on top of a Meteor backend sounds like the right experiment for it, keep us posted!

Binaries: same answer as for xet7, documents yes, files no. S3 for the files sounds right.

Conflicts: with content only writable by its owner, the first version covers you. Server wins, the device gets the server’s version right after replay, and a conflict needs the same user on two devices. Letting the user pick the winner is app UI on top of that: the engine gives you the pending calls and the server’s answer, not the dialog.

Secure storage: in the browser it’s IndexedDB, per origin, protected by the OS session and nothing more. What you get from the engine is control over which collections are kept, plus the clearing on logout or account switch. Encrypting the copy with Web Crypto is possible on top but not in the first version. Data that should never sit on a shared device simply stays out of the list.

Next on my side: updates and removes, the clearing on account switch, then the PR against 3.7. I’ll post here when it’s up :rocket:

1 Like

… :smiling_face_with_horns:
@xet7 @waldgeist the PR is up: feat(offline): keep published documents and queued Method calls on the device by dupontbertrand · Pull Request #14956 · meteor/meteor · GitHub, against 3.7

It ended up smaller than the June prototype, because Meteor already does most of the work: a call made offline sits in its queue and is re-sent on reconnect, and a rejected call gets its stub writes reverted. So the offline package only keeps two things on the device: a copy of the documents your publications sent, for the collections you list, and the calls to the Methods you list, until the server answers. On the next load the copy is in Minimongo before the connection comes back, the pending calls go out once, and the first server data replaces the copy, like a reconnect does :+1:

What you asked for is in: collections and Methods are opt-in, the queue is readable (Offline.pending(), failed(), drop(id)), a rejected call is reported and doesn’t block the others, the copy is per user and deleted on logout, and there is no sync query on the server. Listed Methods have to be idempotent (client id, insert if absent), the README says why :wink:

meteor create --pwa on that branch gives you a links list that works offline if you want to kick the tires. Reviews and “it breaks when I…” reports welcome :folded_hands:

Hi,

Can we have a comparaison between the foreseen implementation and the current jam:offline package ?

Will the new implementation work well with Cordova (and later with Capacitor) ?

Thanks

1 Like

Hey @harry73 :smiling_face:

How it compares to jam:offline

First, credit where it’s due: jam:offline has been the answer to “offline in Meteor” for a good while, and on a few points it does more than the package in PR #14956 (filters, limits, several tabs). The two just make different bets.
jam:offline keeps a capped local cache of all your collections and reconciles it with the server when you’re back. The core package keeps what your publications sent and what your Methods were called with, and lets the publication do the reconciling. Side by side, from the code of both:

jam:offline 0.4.1offline (PR #14956)
Runs onClient and server: a _keep Method reconciles on reconnectClient only, nothing on the server
What is keptAll collections by default, with a filter, a sort on updatedAt and a limit of 100 per collection, or Collection.keep(filter)The collections you list, exactly the documents your publications sent
Deleted documentsOn reconnect the server is asked what stopped matching since the last sync, which needs soft deletes (a deleted flag) or an archive collectionNothing to reconcile: on the next load the first server data replaces the copy, as a reconnect already does, and the deleted document is gone. No convention on your collections
Extra server workOne reconcile query per kept collection on reconnectNone: the publication is sent in full on every load, as it is today in any Meteor app
Queuing a callYour code calls queueMethod(name, args) when it detects it's offline, and calls the Method with noRetry: true (automatic with jam:method)Every call to a listed Method is recorded when it's sent, online or offline, and erased when the server answers. Your calling code doesn't change
ReplayOn reconnect, once a user is logged in, one call after the other; a failed call is reported through handleSyncErrors and droppedOn the next load, logged in or not, one call after the other; a rejected call stays as failed with the server's error, the rest goes on, and Offline.pending(), failed(), drop(id) let you show it
UsersOne local database for the deviceOne database per Meteor.userId(), deleted on logout
Several tabsKept in sync offline through a BroadcastChannelNot handled yet: one tab replays the queue, two tabs replay it twice. A known limit of this first version
Subscriptions while offlineMeteor.subscribe is patched to return a ready handle while the connection status is offlineready() stays false until the connection is back; the documents are in Minimongo anyway, so render from the collection rather than from ready()
What your Methods must doBe isomorphic; an insert returns the new _idBe idempotent (client-side _id, insert if absent): a call can be re-sent after its answer was lost, same as Meteor's own retry
Dependenciesnpm idb; soft deletes or an archive in your schema (jam:soft-delete and jam:archive make that easy)None

In short: if you’d like a capped cache of every collection, with filters, and your schema already has soft deletes or an archive, jam:offline gives you that today, on 2.x too. The core package is the smaller, no-convention option for the opt-in case: a few collections, a few Methods, nothing to add on the server. Both write to Minimongo the same way, so your templates won’t notice which one is underneath.

Cordova now, Capacitor later

Short answer: yes, it should, and I’ll be upfront that I haven’t proven it on a phone yet. Here’s why I’m fairly relaxed about it. The package is a plain client package, so Meteor builds it into the web.cordova bundle like any other.
The only platform API it touches is IndexedDB, which WKWebView on iOS and the system WebView on Android both have. Meteor serves a Cordova app from a fixed local origin (localhost plus a port derived from the app id), so the IndexedDB
database is the same from one launch to the next, and a hot code push is just a reload as far as the package is concerned: copy loaded, queue sent. A Cordova build is the next thing I’ll check once the review settles, Android first. If
you have a 3.x Cordova app around and ten minutes to spare, the branch is dupontbertrand:feature/offline, and I’d love to hear how it goes on a real device.

Capacitor keeps the same model in Nacho’s #14633: Meteor owns the web app and the runtime, Capacitor owns the native projects, and hot code push stays. The package lives in the WebView and doesn’t know which shell is around it, so
there’s nothing to add on either side. Once both are merged, one run on a device should be all it takes :thinking:

Happy to go deeper on any of this :saluting_face:

Thanks for the comparison, @dupontbertrand.

At first glance, this could be an issue for my use case, as it would require changing the behavior of my application, which may impact adoption.

I also rely on jam:pub-sub for .once() publications and subscription caching. This is particularly useful because it allows the application to keep data available when it is launched frequently in offline situations (for example, while traveling or in areas with limited or no connectivity).

1 Like

@harry73 thanks, that’s exactly the kind of feedback I was hoping for, and you’re right about ready(): asking people to rewrite their guards is an adoption tax. I changed it in #14956 today. A subscription made while the connection is down is ready as soon as the copy is in Minimongo, as long as the copy holds documents. ready(), onReady, Template.subscriptionsReady and useSubscribe all see it, because it’s the subscription record itself that gets marked ready, the way the server’s ready message does it. When the connection comes back, the server’s data replaces the copy in one batch and the subscription stays ready, as any subscription does across a reconnection, so no spinner flashes. On a very first start, with nothing on the device, subscriptions wait for the server as before. Your templates stay as they are.

On jam:pub-sub, from reading its code (0.5.1), not from running it with the package yet:

  • Subscription caching is a good match. A cached subscription is a subscription that stays up after the component is gone, so its documents stay in Minimongo, and whatever is in Minimongo is in the copy. cacheDuration: Infinity on the publications you want at launch is the same thing as the “keep the subscription up for the whole session” advice in the package doc
  • .once documents are written straight into Minimongo by jam:pub-sub, so the package copies them like any other and they’re back at the next launch. One thing to know: the handle of a .once publication is jam:pub-sub’s own, and offline its Method waits for the connection, so that ready() stays false until you’re back. That’s the one place where you’d render from the collection, or raise it with Jam, since the package can’t reach that handle. On the next connection the first server data replaces the copy before the .once results are merged in, like on a plain reload, so nothing stale lingers; between reconnections, jam:pub-sub keeps .once data through Meteor’s reset as it does today

I also answered your ObjectID question on the PR: ids are stored as EJSON, so an ObjectID comes back as an ObjectID, and there’s a test for it now :+1:

If you get a chance to run the branch against your app, even for ten minutes, that’s the feedback I can’t produce myself :folded_hands:

1 Like

I will try but need before to remove some jam:offline integrations to compare.

@harry73 no rush, and thanks for being up for it. Two things that may make it cheaper

From claude :
The removal is smaller than it looks. jam:method and jam:pub-sub stay as they are: jam:method only queues a call and sets noRetry when jam:offline is loaded, so without it your calls fall back on Meteor’s own retry, which is what the package builds on. What goes is the jam:offline surface itself: Offline.configure, the .keep filters, queueMethod, handleSyncErrors, isSyncing, clear / clearAll. In their place, one Offline.start({ collections, methods }) at client startup, with Meteor.users in the list if you need Meteor.user() offline (jam:offline keeps it by default), and Offline.on('method.failed') if you tell the user about rejected calls. The one thing with no equivalent is .keep: the copy is what your subscriptions hold, so a bound on its size is a bound on the publication.

From me :
And if you would rather not touch your app yet, the other way round works too: describe your setup and I build a minimal app on the branch that mirrors it, or push a minimal app of your own and I run it. What I would need to know:

  • Cordova (Android, iOS) or web, and your Meteor version
  • which publications are .once, which are cached and with what cacheDuration, and which data has to be there at an offline launch
  • what you use from jam:offline: .keep filters (with Meteor.userId()?), queueMethod or jam:method, handleSyncErrors, isSyncing
  • whether the app starts logged in while offline, and what it shows of Meteor.user() then
  • which collections use ObjectID ids

Web first on my side; Cordova Android is still on my list

Hi @dupontbertrand, thanks for asking for requirements before going further.

Our case: a Meteor 3 + React PWA for personal accounting. Three things we’d need, most important first.

1. EJSON custom types inside documents, not only in IDs
Our amounts are Decimal from mongo-decimal. Written to IndexedDB as they are, documents with a Decimal instance fail on structured clone (DOMException: Function object could not be cloned).

Does the PR store whole documents with EJSON.toJSONValue / EJSON.fromJSONValue, or only the _id? If it’s the whole document, a test with a type registered through EJSON.addType (Decimal is a good one) would cover it.

Related point: the device copy is loaded into Minimongo before the connection is up, so custom types must already be registered at that moment. That’s fine for mongo-decimal, which registers when the package loads, but an EJSON.addType call in app code could run later. Worth a line in the docs.

2. Idempotent inserts with a client-generated _id
Our insert Methods accept an _id generated on the client, so the offline stub and the replay create the same document. A replay after a lost response then hits a duplicate key error on the server.

Which pattern do you have in mind? Either the Method treats an existing _id written by the same user as success, or the package sends a call id the server can check. A short example in the docs would help, since every listed insert Method needs one.

3. The device copy when a subscription stops
When a subscription stops, for example because the component that opened it unmounts, Minimongo drops its documents. Does the device copy follow Minimongo and remove them, or does it keep what publications sent until the next online load? We need the second: a record opened once should still be there offline.

@davideonmeteor thanks, this is exactly the kind of list I was after, and a personal accounting app is a good test for the copy :wink: In order:

1. Custom EJSON types. The copy holds whole documents and the recorded calls hold their arguments, both as EJSON strings: documents and arguments reach IndexedDB as strings, so nothing of yours goes through structured clone. A Decimal from mongo-decimal comes back as a Decimal, the way a Mongo.ObjectID does today (there is a test for that one). You are right about the timing: Offline.start is what loads the copy, so a type registered after it fails with Custom EJSON type X is not defined. mongo-decimal registers at package load, so it is fine; an EJSON.addType in app code has to run before Offline.start. Both are in the branch now: a test with a type registered through EJSON.addType, in a document field and in a recorded call, and the line in the README.

2. Idempotent inserts. The Method treats an existing _id as success, with an upsert and $setOnInsert. This is what links.insert does in the --pwa skeleton, and the README now shows it:

Meteor.methods({
  async 'links.insert'({ _id, title, url }) {
    await Links.upsertAsync({ _id }, { $setOnInsert: { title, url, createdAt: new Date() } });
  },
});

The same function runs as the stub, so a replay after a reload is a no-op on the device too. No call id on the wire: Meteor itself re-sends a call that was sent but never answered, with or without this package, so a listed Method has to be safe to run twice anyway, and the upsert is the cheapest way there.

3. The copy when a subscription stops. I’m trying to be clear; if I’m not, I’ll go into more (or less) detail :joy: It follows Minimongo, with one detail that matters for your case. Offline, a subscription that stops only queues its unsub: the documents stay until the next connection, so a record opened earlier in the session is still there offline, across a reload too. Online, when the component unmounts, the server withdraws the documents and the copy drops them with Minimongo. For “opened once, always there offline”, the pattern is a subscription that lives for the session rather than for the component: a Meteor.subscribe('records.opened', ids) at app level, with the ids the user opened kept in a reactive list, and the publication serving those ids. The records then stay in Minimongo, in the copy, and fresh, and they leave when the user clears the list. That is the design of this version: the device holds what the publications currently send, nothing more, so an offline record is never one the server has stopped sending. I’m adding “keep what was published once” to the requirements with your case as the example. Does the session-level subscription cover it, or do you need records to outlive what the server still publishes?

Thanks, all three are clear.

The session-level subscription covers our case. What we need offline is a known set (accounts, recent transactions, templates), so app-level subscriptions fit, and I like that the device never keeps something the server stopped sending.

On point 2: good reminder that Meteor re-sends unanswered calls anyway. We’ll make our inserts idempotent on the client `_id` now, independently of the package.

1 Like