Access Data Offline in JavaScript Applications
Configure a local cache for selected relations, query cached rows, and queue relational writes when the client cannot reach the backend.
How Offline Data Access Works
Offline support is optional and applies to relations you explicitly configure. The SDK maintains cached rows and queued mutations for those relations. Other relations retain normal request behavior.
Use the same relational query builder for online and local operations. Select cached data with fromCache() and inspect the response’s offline metadata.
A local query can contain incomplete or stale data. A locally queued write is not proof that the backend has accepted it.
Before You Begin
Use a relational project with a registered web app and an initialized client. These examples use TODOS(ID, TITLE, COMPLETED), with a stable ID primary key and DDS Data Grants that permit the reads, inserts, and updates.
The configured relation name must match from("todos"). Use returned column names exactly for cache keys, local projections, filters, and write values. Cache lookups are case-sensitive; the unquoted Oracle table returns ID, TITLE, and COMPLETED.
Use a browser with IndexedDB for persistence across reloads, or choose memory persistence for the page’s lifetime. Configure persistence before performing the reads and writes that you want cached.
Configure Offline Persistence
Import offline functions from the relational package and provide relation-key settings:
import {
enableOffline,
persistentLocalCache,
} from "@fusabase/fusabase-relational";
await enableOffline(
client,
persistentLocalCache({
synchronizeTabs: false,
relations: {
todos: { primaryKey: ["ID"] },
},
})
);
The examples in this chapter use one project schema and a single tab. Define client using your Console-generated configuration before calling enableOffline().
| Property | Type | Purpose |
|---|---|---|
relations |
Object | Required mapping from relation names to primaryKey column arrays. |
persistence |
"indexeddb" or "memory" |
Storage engine; the default is "indexeddb". |
cacheSizeBytes |
Number | Approximate cached-row size limit; omitted means no configured limit. |
synchronizeTabs |
Boolean | Requests tab coordination; the default is false. |
Await enableOffline() before issuing cache reads or writes.
Use IndexedDB Persistence
Use enableIndexedDbPersistence(client, options) as an alternative to the preceding configuration:
import {
enableIndexedDbPersistence,
} from "@fusabase/fusabase-relational";
await enableIndexedDbPersistence(client, {
relations: {
todos: { primaryKey: ["ID"] },
},
});
IndexedDB retains cached rows and queued mutations across page reloads. Choose this behavior only when retaining application data on the device is appropriate.
Use Memory Persistence
For page-lifetime storage, choose memory persistence instead:
import { enableMemoryPersistence } from "@fusabase/fusabase-relational";
await enableMemoryPersistence(client, {
relations: {
todos: { primaryKey: ["ID"] },
},
});
Memory data and unsynchronized writes are lost when the page or process ends. Choose one persistence configuration for the walkthrough; these snippets show alternatives.
Configure Cache Size and Multi-Tab Synchronization
Set cacheSizeBytes when enabling persistence to limit the approximate size of cached rows. Rows affected by pending local writes are protected from cache eviction.
For an application that uses multiple tabs, synchronizeTabs: true coordinates shared cache state and replay. A secondary tab can forward a read to an online primary tab even after disableNetwork() is called in the secondary tab. Use fromCache() when a read must stay local.
Read and Query Cached Data
First read data from the backend while online. Include the configured primary-key columns in the projection:
const primed = await client
.from("todos")
.select("ID,TITLE,COMPLETED")
.order("ID");
if (primed.error) {
throw primed.error;
}
if (primed.offline?.fromCache) {
throw new Error("The cache-warming query did not reach the backend.");
}
Array results with valid keys can populate the row cache. A projection that omits the configured keys does not provide usable row identities. Do not rely on single() or maybeSingle() queries to populate the cache.
Read the same query from the cache:
const cached = await client
.from("todos")
.select("ID,TITLE,COMPLETED")
.order("ID")
.fromCache({ requireComplete: true });
if (cached.error) {
throw cached.error;
}
console.log(cached.data);
requireComplete: true rejects a cache query whose complete target has not been recorded locally. It does not establish freshness against the backend. Without it, a cache query can return partial local results.
Local evaluation supports filters, logical groups, ordering, ranges, single-row result modifiers, and basic aggregates. Related-table projections are not supported by the cache evaluator.
Inspect Offline Response Metadata
Relational responses can include offline metadata:
console.log(cached.offline?.fromCache);
console.log(cached.offline?.hasPendingWrites);
fromCache indicates that local evaluation produced the response. hasPendingWrites indicates that queued local mutations affect the local view.
Inspect this metadata on query responses when rendering pending state. It is response metadata, not a subscription API.
Disable and Enable Network Access
Use disableNetwork() for the configured relations in a single-tab application:
import { disableNetwork } from "@fusabase/fusabase-relational";
await disableNetwork(client);
Reads of configured relations use the local path and writes queue locally. Relations omitted from relations continue to use normal requests.
Use enableNetwork() to resume delivery. For a read that must use the cache regardless of tab coordination, use fromCache().
Write Data and Monitor Synchronization
When configured relations are operating locally, supported writes update the local view and enter the queue. A local response can have HTTP-style status 202 and offline.hasPendingWrites set to true.
When network access is available, a write can execute against the backend instead. Do not treat all writes on an offline-enabled client as local-only completions.
Requirements for Offline Updates
Local updates and deletions evaluate their filters against cached rows. Cache the rows and their keys before losing connectivity, and use filters that identify the intended rows.
For example, update one cached row:
const changed = await client
.from("todos")
.update({ COMPLETED: true })
.eq("ID", todoId);
Set todoId to an identifier present in the local cache. A filter over an incomplete cache cannot establish that all matching backend rows were considered.
Insert Rows While Offline
Supply stable key values when inserting rows locally. The cache needs the configured key to identify each pending row.
const queued = await client
.from("todos")
.insert({
ID: -1001,
TITLE: "Prepare release while offline",
COMPLETED: false,
});
if (queued.error) {
throw queued.error;
}
This example uses -1001 as an illustrative key. Choose an unused identifier using your application’s key-allocation strategy. A backend-generated identity is not available for a row that has only been queued locally.
Resume network delivery, then wait for the local write queue to finish processing:
import {
enableNetwork,
waitForPendingWrites,
} from "@fusabase/fusabase-relational";
await enableNetwork(client);
await waitForPendingWrites(client);
Offline Write Boundaries
Arrays of rows can be submitted through insert() and upsert(). Queuing a mutation does not establish a transaction across separate SDK calls.
The public relational client does not expose a multi-operation client transaction API. See Batch Writes.
Clear Persistent Offline Data
Use clearIndexedDbPersistence(client) to clear the client’s opened local stores after offline support has been enabled:
import {
clearIndexedDbPersistence,
} from "@fusabase/fusabase-relational";
await clearIndexedDbPersistence(client);
Caution: Clearing these stores discards cached rows and pending mutations. Clear them only when the application intends to discard that offline state.
Calling this function before offline support is enabled does not clear stores from an earlier application session. Do not use a clear-before-enable sequence as a cleanup procedure.
Security and Offline Limitations
Backend requests remain subject to authentication, App Trust requirements, and DDS authorization. Local cache evaluation does not re-evaluate backend Data Grants.
Keep the following limits in mind:
- Cached data can be incomplete or stale.
- Rows need valid configured primary-key values.
- Local relation projections are unsupported.
- Cached aggregates operate on local rows, not the complete backend table.
- Network controls affect configured relations, not every request made by the client.
- Memory persistence does not survive the page lifetime.
- Clearing cache state can discard queued writes.
Offline API Summary
The relational package exports the following functions:
| API | Purpose |
|---|---|
enableOffline(client, options) |
Enable relation-specific cache and mutation queuing. |
persistentLocalCache(options) |
Build IndexedDB options, including required relation-key settings. |
enableIndexedDbPersistence(client, options) |
Enable IndexedDB persistence. |
enableMemoryPersistence(client, options) |
Enable page-lifetime memory storage. |
isOfflineEnabled(client) |
Inspect whether offline state is registered. |
disableNetwork(client) |
Disable direct network use for configured relations in the calling tab. |
enableNetwork(client) |
Resume network use and request queued-write replay. |
waitForPendingWrites(client) |
Wait for the local write queue to finish processing. |
clearIndexedDbPersistence(client) |
Clear currently opened offline stores. |
shutdownOffline(client) |
Close offline state for the client. |
Use select(...).fromCache(options) on the query builder for cache reads. Inspect result.offline on responses for cache and pending-write metadata.