@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 |
|---|---|---|
handleTapiRequest |
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, typically from the activate event. |
CleanupOptions |
type | Options for cleanup. |
Logger |
type | Re-exported from @toapi/common; the optional logger accepted by handleTapiRequest. |
Minimal service worker
Section titled “Minimal service worker”import { handleTapiRequest, listenForInvalidations, cleanup,} from "@toapi/worker";
declare const self: ServiceWorkerGlobalScope;
self.addEventListener("activate", (event) => { event.waitUntil(cleanup({ maximumStaleAge: 60 * 60 * 24 * 7 }));});
self.addEventListener("fetch", (event) => { const url = new URL(event.request.url); if ( url.pathname.startsWith("/api") && !url.pathname.startsWith("/api/__tapi") ) { event.respondWith(handleTapiRequest(event.request)); }});
listenForInvalidations({ url: "/api/__tapi/invalidations" });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.