@toapi/worker
@toapi/worker is the service-worker half of the Toapi caching system. It runs
inside a browser Service Worker
and intercepts requests to your Toapi endpoints, transparently caching responses
in Cache Storage and
tracking their cache tags and expiry in IndexedDB.
Together with the server’s revalidation stream this gives you:
- Instant reads — cached responses are served without hitting the network.
- Tag-based revalidation — when the server invalidates a tag, the worker marks every affected cache entry as stale so it is refetched on next access.
- Offline resilience — if the network is unavailable, an expired-but-present cache entry is served rather than failing.
Installation
Section titled “Installation”npm install @toapi/workerThe package targets the WebWorker type lib rather than the DOM lib. See the
service-worker guide for the tsconfig.json
setup and the full build/register recipe.
Public API
Section titled “Public API”| Export | Kind | Purpose |
|---|---|---|
setupToapiWorker |
function | Set up the whole worker in one call: registers the listeners and opens the stream. |
handleToapiRequest |
function | Handle a single fetch event: serve from cache, network, or invalidate on mutation. |
listenForInvalidations |
function | Open the server’s revalidation stream and apply remote tag invalidations. |
cleanup |
function | Reconcile the cache and metadata stores; run once on worker startup. |
SetupToapiWorkerOptions |
type | Options for setupToapiWorker. |
CleanupOptions |
type | Options for cleanup. |
Logger |
type | Re-exported from @toapi/common; the optional logger accepted by handleToapiRequest, listenForInvalidations, and setupToapiWorker. |
Minimal service worker
Section titled “Minimal service worker”The whole worker is a single call:
import { setupToapiWorker } from "@toapi/worker";
declare const self: ServiceWorkerGlobalScope;
setupToapiWorker();By default this caches same-origin requests under /api (excluding the
/api/__tapi control endpoints), listens for invalidations on
/api/__tapi/invalidations, and runs a cleanup pass on every worker startup. Pass options to change the base path, stream URL,
stale window, or logger:
setupToapiWorker({ basePath: "/data", maximumStaleAge: 60 * 60 * 24, // 1 day});If you need to interleave Toapi with your own fetch logic, you can
wire up cleanup,
handleToapiRequest, and
listenForInvalidations by
hand instead — see the
service-worker guide.
Related
Section titled “Related”- Service worker setup guide
@toapi/cache— the server-side tag-based cache that produces the tags and expiry headers this worker reads.