Skip to content

Offline Support ​

Homestead apps keep working when the network drops. Reads serve the last data you saw, writes apply instantly and queue, and everything syncs to the server when the connection returns. If you build your app the standard way — resources plus the standard data hooks — you get this for free, with no offline code to write.

This page covers:


What you get for free ​

Any resource you read and write through the standard hooks is offline-ready the moment you define it. No setup, no flags.

While offline:

  • Reads return cached data. A useQuery (or a hook like useGiftCards) serves whatever it last loaded instead of failing.
  • Writes apply immediately. A create, update, or delete updates the screen right away, then waits in the outbox. Both the collection list and the edited record's own detail view reflect the change, so the two never disagree.
  • The outbox drains on reconnect. Queued writes are sent in order, oldest first, and the affected lists refetch so the screen matches the server.
  • A failed write rolls back. If the server rejects a queued write when it finally runs, the change is undone and the reason is shown as a toast.

Online, a write still waits for the server's answer, so a validation error rejects mutateAsync as usual and a form can stay open to show it.

The outbox: writes as AEP requests ​

Every queued write is stored as the AEP standard method it will be sent as, addressed by the record's AEP-122 resource name — the same path every record carries (homestead-core/api/outbox.ts):

WriteSent asReplaying it
createAEP-133 POST {parent}/{collection}?id={id} — the client picks the idA 409 on that id means an earlier attempt landed; that record is adopted
updateAEP-134 PATCH {name}, an RFC 7396 JSON Merge PatchApplying a merge patch twice changes nothing more
deleteAEP-135 DELETE {name}?force=trueA 404 means it's already gone — done

Because the client chooses a new record's id, the record has its final id and name from the moment it's created, offline or not: you can link to it, edit it, or add children under it straight away, with nothing to reconcile later. And because each entry is a standard method on a named resource, the outbox can reason about writes without knowing which app made them:

  • Writes to one record collapse. A create then an update is sent as one create; two updates as one merged patch; a create then a delete is never sent at all (nor is anything created beneath it).
  • Reads include what's queued. A list read from the server, or restored from the device, shows the queued creates, updates and deletes applied on top — so a refetch mid-queue, or a cache snapshot older than the person's last changes, never hides them.
  • "Waiting to sync" survives a reload. usePendingSync reads the outbox, which is saved on the device after every change.

The cache survives a page reload, too. A user can close the tab on the subway, reopen it still underground, and see their data (kept for up to 7 days). It is saved in the browser's IndexedDB (localStorage only where IndexedDB is unavailable), at most every two seconds and immediately when the app is hidden, so a write made just before switching away is kept.

Secret fields never reach the device. Fields declared encrypted or secret — a gift card's number and PIN, the household Wi-Fi password — are stripped from everything the cache saves (homestead-core/api/redactSecrets.ts). While the app is open they show as usual; after a cold offline start the record is there without them until it can refetch, so render a missing secret as "Available when online" rather than as blank. A queued write whose own input carries a secret (changing a PIN offline) stays queued in memory only: it syncs as long as the app stays open, but not across a restart.

Queued writes outlive the cache. Cached reads are dropped when the server ships a new build or after 7 days; the outbox is saved separately and is never dropped, so a server update or a week without signal never loses what someone did offline. Signing out (or a different person signing in) clears it.

The app itself opens offline, too. The service worker precaches the app shell — index.html, styles, and the code of every app's screens — so an app added to the Home Screen launches with no network, even one the person has never opened before. A navigation tries the network first (so an online launch always gets the current build) and falls back to the cached shell when the network fails or takes more than a few seconds. Code that only a library loads on demand (syntax-highlighting grammars, diagram renderers), plus the packages listed in lazyPackages in packages/homestead-app/vite.config.ts, is cached the first time it loads instead. Each build ships a new worker, which replaces the previous build's cache. Nothing to do in your app: the build works out what to cache (packages/homestead-app/vite/offline-precache.ts). Dev mode caches nothing.

You opt into all of this by using the standard write hooks from State Management:

ts
import { useResourceCreate } from '@rambleraptor/homestead-core/api/resourceHooks';

export const useCreateGiftCard = () =>
  useResourceCreate<GiftCard, GiftCardFormData>('gift-cards', 'gift-card');

These hooks carry the offline behavior for you. The only requirement is the mutation key — ('<appId>', '<singular>'), which useResourceCreate, useResourceUpdate, and useResourceDelete set automatically.

If you hand-write a useMutation (for file handling or a multi-step write), match that key to inherit the same offline queue:

ts
import { useMutation } from '@tanstack/react-query';
import { resourceMutationKeys } from '@rambleraptor/homestead-core/api/registerResourceMutationDefaults';

const keys = resourceMutationKeys('gift-cards', 'gift-card');

useMutation({ mutationKey: keys.create /* , ...your overrides */ });

A useMutation with no matching key is not offline-aware: it will fail outright when there's no network.


Show offline state in your UI ​

A global banner already tells users when they're offline — "You are offline. Changes will sync when you reconnect." — pinned to the bottom of every screen. It's part of the app shell, so you don't add it yourself.

When you need the offline state inside a component, use useOnlineStatus:

tsx
import { useOnlineStatus } from '@rambleraptor/homestead-core/shared/hooks/useOnlineStatus';

function SyncHint() {
  const { isOffline } = useOnlineStatus();
  if (!isOffline) return null;
  return <p>Saved on this device — will sync when you're back online.</p>;
}

It returns { isOnline, isOffline } and re-renders the moment the connection changes.


Disable actions that need the network ​

Some actions can't be queued because they have no offline meaning — sending a test notification, running a chat request, kicking off a server job. Disable those controls while offline so users don't trigger a guaranteed failure:

tsx
const { isOffline } = useOnlineStatus();

<button
  disabled={isOffline}
  title={isOffline ? 'Available when you reconnect' : undefined}
>
  Send test notification
</button>

Regular create/update/delete buttons do not need this — they queue and sync on their own.


Handle file uploads ​

Writes that send a file (anything using FormData, such as a resource with a file field) are not queued offline. A file upload needs the network and fails when there isn't one.

Guard any upload path with the online check:

tsx
const { isOffline } = useOnlineStatus();

<button disabled={isOffline}>Upload receipt</button>

Text-only writes on the same resource still queue normally — only the file-carrying write is online-only.


Customize per resource ​

The default offline behavior fits standard CRUD, and the factory derives everything it needs — list cache key, mutation keys, optimistic shape, request body, and each record's resource name — from the resource definition. There are no per-resource config overrides.

Cascade a delete. When deleting one record should also delete or fix up related records, compose the standard hooks in a hand-written hook rather than issuing the related writes directly, so each one stays optimistic and offline-queued. useDeleteStore (groceries) reads the store's items from the cache and fires a normal grocery-delete for each before deleting the store:

ts
// packages/homestead-apps/groceries/hooks/useDeleteStore.ts
const deleteStore = useResourceDelete('groceries', 'store');
const deleteItem = useDeleteGroceryItem();

// inside the wrapped mutate(storeId):
const items = queryClient.getQueryData<GroceryItem[]>(ITEMS_KEY) ?? [];
for (const it of items) {
  if (it.store === storeId) deleteItem.mutate(it.id); // optimistic + queued
}
deleteStore.mutate(storeId);

Reading the member list from the cache (not the network) keeps the cascade working offline; each deleteItem.mutate inherits the grocery resource's optimistic removal and its place in the outbox.

Nested resources need no wiring. A resource with parents declared on its definition (e.g. a perk parented by credit-card, or a redemption two levels deep) gets full offline CRUD automatically. A create goes under its parent's resource name (the parent record's path, found through the parent field in the create variables); an update or delete uses the record's own path. The parent field stays on the cached record for joins but is never sent in the request body — the name carries it. Point your read hook at the resource's convention keys — queryKeys.app(appId).resource(singular).list() for a collection and .detail(id) for one record — so it reads from the same place the factory writes, and use the plain useResource* wrappers for writes. The generic useResourceList and useResourceItem hooks already use those keys. A detail hook on some other key still refreshes online (the settle-time invalidation covers the whole app), but it will show stale data offline, where there is no invalidation to reconcile it.


Reference ​

ItemImportUse
useResourceCreate / useResourceUpdate / useResourceDelete@rambleraptor/homestead-core/api/resourceHooksOffline-ready CRUD hooks
resourceMutationKeys(appId, singular)@rambleraptor/homestead-core/api/registerResourceMutationDefaultsMutation keys for a hand-written useMutation
useOnlineStatus()@rambleraptor/homestead-core/shared/hooks/useOnlineStatus{ isOnline, isOffline }, reactive
usePendingSync(id) / usePendingSyncIds()@rambleraptor/homestead-core/api/usePendingSyncWhich records have a write waiting for a connection
<PendingSyncBadge />@rambleraptor/homestead-core/shared/components/PendingSyncBadge"Waiting to sync" marker for a row
outbox@rambleraptor/homestead-core/api/outboxThe queued AEP requests (read-only for apps)
<OfflineBanner />(in the app shell)Global offline banner — already mounted

Offline behavior at a glance:

Action offlineWhat happens
Open the appLoads from the cached shell (network first, falls back after ~4s)
Read a resourceServes cached data (kept up to 7 days, survives reload)
Read a secret field after an offline restartMissing until the next refetch — never stored on the device
Create / update / deleteApplies on screen, queues in the outbox, syncs on reconnect (oldest first)
Several writes to one recordCollapse into one request (or none, for create + delete)
App updated (or 7+ days) before reconnectingCached reads dropped; the outbox is kept and sent
Queued write rejected by serverOptimistic change rolls back
Upload a fileFails — uploads are online-only
Action with no offline meaningYou disable it via useOnlineStatus