Skip to Content
Client Lib

Offline

An outbox that saves work done offline and sends it when you are back online.

Usage

import { createOutbox } from "@dapplelight/signet-lib/offline"
import { indexedDbStorage } from "@dapplelight/signet-lib/storage"
import { api } from "./api"
import type { NewExpense } from "./types"

const outbox = createOutbox<NewExpense>({ storage: indexedDbStorage() })

async function saveExpense(expense: NewExpense) {
  if (!navigator.onLine) return outbox.add(expense)
  await api.post("/expenses", expense)
}

addEventListener("online", () =>
  outbox.flush((expense, id) => api.post("/expenses", expense, { headers: { "Idempotency-Key": id } })),
)

send must be safe to repeat for the same id. A crash between sending and removing can deliver an item twice, so send id as an idempotency key.

API

ExportWhat it does
createOutbox<T>(options)Returns an Outbox<T>
OutboxOptions, OutboxTypes

createOutbox(options)

OptionTypeDefault
storageStorageAdapterrequiredAny adapter from Storage
keystring"signet-outbox"One per outbox

Outbox methods

MethodReturns
add(item)The new item's id
count()Items waiting
flush(send)Sends each item in order, removes sent ones, keeps failures. Resolves to how many were sent
clear()Drops everything

One flush runs at a time. Where Web Locks exist, tabs and the service worker sharing a key take turns. Items are stored as one JSON array: fine for hundreds, not thousands.