How the Layers SDK handles caching, request deduplication, and persistence to local storage so your storefront feels fast and avoids duplicate API calls.
Cached results are restored from local storage on back navigation:
// Initial page loadconst collection = client.collection({ handle: 'shirts' })await collection.execute() // Makes API call, caches result// User navigates away and returns via back button// Cache is restored from localStorage - no API call needed
Cache persistence is pluggable via a StorageAdapter. The SDK ships two adapters and accepts any custom implementation, so the cache survives reloads in the browser, page navigations in SSR frameworks, or process restarts in Node.
localStorageAdapter returns null in environments without window.localStorage (e.g. SSR), so the SDK silently falls back to in-memory caching — safe to use in isomorphic code.
The adapter takes a minimal FileSystem interface (readFileSync, writeFileSync, unlinkSync), so you can substitute a mock in tests or wrap an alternative file system.
All three adapter methods are synchronous and operate on a single serialized JSON string. Wrap async backends in a sync queue or memoize the latest snapshot if you need IndexedDB or remote storage.See Cache, storage, and signals for the full interface reference.
The SDK calls the global fetch by default. Provide a custom implementation via the fetch option for SSR runtimes, testing, or environments where fetch is unavailable or blocked.
import type { CustomFetch } from '@commerce-blocks/sdk'type CustomFetch = (url: string, init?: RequestInit) => Promise<Response>
xhrFetch is an XMLHttpRequest-based adapter shipped with the SDK. Use it when ad blockers, browser extensions, or restrictive network policies intercept fetch calls:
The SDK handles retries, abort signals, and error classification on top of whatever fetch returns — your adapter only needs to issue the request and return a Response.